<!DOCTYPE html>
<html class="wf-nojavascript">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<link href="favicon.ico" rel="icon" type="image/x-icon"/>
<link href="touch_icon_152x152.png" rel="apple-touch-icon" sizes="152x152"/>
<link href="touch_icon_144x144.png" rel="apple-touch-icon" sizes="144x144"/>
<link href="touch_icon_120x120.png" rel="apple-touch-icon" sizes="120x120"/>
<link href="touch_icon_114x114.png" rel="apple-touch-icon" sizes="114x114"/>
<link href="touch_icon_72x72.png" rel="apple-touch-icon" sizes="72x72"/>
<link href="touch_icon_60x60.png" rel="apple-touch-icon" sizes="60x60"/>
<link href="touch_icon_57x57.png" rel="apple-touch-icon" sizes="57x57"/>
<link href="touch_icon_57x57.png" rel="apple-touch-icon"/>
<link href="startup_image_320x480.png" rel="apple-touch-startup-image"/>
<script type="text/javascript">
// allows non-javascript browsers to render with fallback fonts
document.getElementsByTagName("html")[0].className = "";

/*
  WebFont.load({
    google: {
      families: ['Open Sans', 'Droid Sans Mono']
    }
  });
*/
// link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'
// link href='http://fonts.googleapis.com/css?family=Droid+Sans+Mono' rel='stylesheet' type='text/css'

WebFontConfig = {
    google: {
      families: ['Open Sans', 'Droid Sans Mono']
    }
};

// http://kevindew.me/post/47052453532/a-fallback-for-when-google-web-font-loader-fails
(function() {
    var wf = document.createElement('script');
    wf.src = 'webfont.js';
    wf.type = 'text/javascript';
    wf.async = 'true';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(wf, s);
    setTimeout(function() {
        if (!("WebFont" in window)) {
            document.getElementsByTagName("html")[0].className += " wf-fail";
        }
    }, 1000);
})();
</script>
<!-- combined stylesheet -->
<link href="style.css" rel="stylesheet" type="text/css"/>
<title>Duktape 编程指南</title>
</head>
<body>
<div id="site-top">
<div id="site-top-logo">
<strong id="logo">((o) Duktape</strong>
</div> <!-- site-top-logo -->
<div id="site-top-nav">
<ul>
<li><a href="index.html">首页</a></li>
<li><a href="http://www.duktape.org/download.html">下载</a></li>
<li><a href="api.html">API</a></li>
<li class="selected"><a href="guide.html">编程指南</a></li>
<li><a href="http://wiki.duktape.org/">Wiki</a></li>
<li><a href="http://www.duktape.org/dukweb.html">REPL</a></li>
</ul>
</div> <!-- site-top-nav -->
</div> <!-- site-top -->
<div id="site-dummy-github" style="position:relative">
<a href="https://github.com/svaarala/duktape"><img alt="Fork me on GitHub" src="forkme_right_gray_6d6d6d.png" style="position: absolute; top: 0; right: 0; border: 0;"/></a>
</div>
<div id="site-middle">
<div id="site-middle-nav"><ul>
<li><a href="#introduction">介绍</a></li>
<li><a href="#gettingstarted">入门指南</a></li>
<li><a href="#programming">Programming model</a></li>
<li><a href="#stacktypes">Stack types</a></li>
<li><a href="#ctypes">API C types</a></li>
<li><a href="#typealgorithms">Type algorithms</a></li>
<li><a href="#duktapebuiltins">Duktape built-ins</a></li>
<li><a href="#postes5features">Post-ES5 features</a></li>
<li><a href="#custombehavior">Custom behavior</a></li>
<li><a href="#customjson">Custom JSON formats</a></li>
<li><a href="#customdirectives">Custom directives</a></li>
<li><a href="#bufferobjects">Buffer objects</a></li>
<li><a href="#errorobjects">Error objects</a></li>
<li><a href="#functionobjects">Function objects</a></li>
<li><a href="#datetime">Date and time</a></li>
<li><a href="#random">Random numbers</a></li>
<li><a href="#debugger">Debugger</a></li>
<li><a href="#modules">Modules</a></li>
<li><a href="#logging">Logging</a></li>
<li><a href="#finalization">Finalization</a></li>
<li><a href="#coroutines">Coroutines</a></li>
<li><a href="#virtualproperties">Virtual properties</a></li>
<li><a href="#symbols">Symbols</a></li>
<li><a href="#bytecodedumpload">Bytecode dump/load</a></li>
<li><a href="#threading">Threading</a></li>
<li><a href="#sandboxing">Sandboxing</a></li>
<li><a href="#performance">Performance</a></li>
<li><a href="#memoryusage">Memory usage</a></li>
<li><a href="#compiling">Compiling</a></li>
<li><a href="#portability">Portability</a></li>
<li><a href="#compatibility">Compatibility</a></li>
<li><a href="#versioning">Versioning</a></li>
<li><a href="#limitations">Limitations</a></li>
<li><a href="#comparisontolua">Comparison to Lua</a></li>
</ul></div> <!-- site-middle-nav -->
<div class="content" id="site-middle-content"><div class="main-title"><strong>Duktape 编程指南</strong></div><hr/><h1 class="sectiontitle" id="introduction">介绍 <a class="sectionlink" href="#introduction">§</a></h1><p>版本号: 2.0.0
(2017-01-02)</p><h2 class="sectiontitle" id="introduction.1">文档介绍范围 <a class="sectionlink" href="#introduction.1">§</a></h2><p>本指南介绍了如何在程序中使用 Duktape 。一旦你掌握了基础知识，可通过简明的 <a href="api.html">API参考</a> 来查找API的细节。 <a href="http://wiki.duktape.org">Duktape Wiki</a> 则提供了更详细的示例和最佳实践。</p><p>本文档不会覆盖 Duktape 的内部实现细节，如果你想修改它们可参阅 
<a href="https://github.com/svaarala/duktape/tree/master/doc">Duktape 库文件</a> 。</p><h2 class="sectiontitle" id="introduction.2">什么是 Duktape? <a class="sectionlink" href="#introduction.2">§</a></h2><p>Duktape 是一个嵌入式的Ecmascript E5/E5.1引擎，专注于可移植性和低空间占用。只要将 Duktape 集成到您的 C/C++ 项目中，就可以通过脚本轻松扩展程序的功能。您还可以在 Ecmascript 中构建程序的主流程，并使用运行快速的C代码函数执行较繁重的工作。</p><p>可嵌入性意味着 Duktape 对底层平台的能力做了最小的假设; 嵌入 Duktape 的应用程序控制着要提供哪些本地绑定以及以什么方式来进行。例如，目前没有将文本打印到控制台或与文件系统交互的默认绑定。 Duktape 发布的包包括了示例程序，如果需要，您可以轻松地集成到你的项目中。</p><p>Ecmascript 和 Javascript 通常被认为差不多是等同的，尽管 Javascript 及其变种在技术上只是使用 Ecmascript 语言的一个环境。两者之间的界限在实践中并不是很清晰：即使非浏览器 Ecmascript 环境通常也提供一些浏览器特定的内置特性。即使如此，我们还是使用 Ecmascript 一词来指代 Duktape 实现的语言。</p><h2 class="sectiontitle" id="introduction.3">一致性 <a class="sectionlink" href="#introduction.3">§</a></h2><p>Duktape 符合自 ES2015 或之后更新的 ES5.0/ES5.1 语义规范：</p><ul>
<li><a href="http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262%205th%20edition%20December%202009.pdf">ECMAScript 语言规范第 5 版</a></li>
<li><a href="http://www.ecma-international.org/ecma-262/5.1/">ECMAScript® 语言规范第 5.1 版</a></li>
</ul><p>Duktape 跟踪最新 Ecmascript 语义规范及内置特性（但是对 ES2015 或更高版本的支持仍然不完整），请参阅：</p><ul>
<li><a href="http://www.ecma-international.org/ecma-262/6.0/">ECMAScript® 2015 语言规范</a></li>
<li><a href="http://www.ecma-international.org/ecma-262/7.0/">ECMAScript® 2016 语言规范</a></li>
</ul><p>在某些特定情况下，Duktape 可能会遵循规范草案，具体参见 <a href="https://github.com/tc39/ecma262">TC39/ecma262</a> 中正在进行的工作。当最新规范中的一个特性与现实中的代码冲突时（例如， <a href="https://github.com/tc39/ecma262/pull/263">RegExp.prototype 问题</a> ），我们将这样做。</p><p>TypedArray 的支持是基于 ES2016 TypedArray; 初始的实现是基于Khronos TypedArray规范：</p><ul>
<li><a href="https://www.khronos.org/registry/typedarray/specs/latest/">Typed Array 规范 (编者起草于2013-07-18)</a> (注意：链接是最新的)</li>
<li><code>svn co -r 30720 https://cvs.khronos.org/svn/repos/registry/trunk/public/typedarray</code></li>
</ul><p>Node.js Buffer 的支持基于:</p><ul>
<li> <a href="https://nodejs.org/docs/v6.9.1/api/buffer.html">Buffer Node.js v6.9.1</a></li>
</ul><h2 class="sectiontitle" id="introduction.4">特性 <a class="sectionlink" href="#introduction.4">§</a></h2><p>除了标准的 Ecmascript 功能，Duktape 还具有以下附加功能（一些是应用程序可见，而其他则是仅内部可见）：</p><ul>
<li>ES2015 <a href="https://www.khronos.org/registry/typedarray/specs/latest/">TypedArray</a> 和 <a href="https://nodejs.org/docs/v6.9.1/api/buffer.html">Node.js Buffer</a> 绑定、纯 buffer 类型 (轻量级 Uint8Array)</li>
<li>Ecmascript 2015 (ES6) 特性：<code>setPrototypeOf</code>/<code>__proto__</code>、 <code>代理(Proxy)</code> 对象子集、<code>反射</code>、可计算属性名称和最小 <code>const</code> 支持</li>
<li>Ecmascript 2016 (ES7) 特性：乘方操作符 (<code>**</code>, <code>**=</code>)</li>
<li><a href="https://encoding.spec.whatwg.org/#api">编码 API</a> 绑定基于 WHATWG 编码标准</li>
<li>Duktape 特有内置特性：由 <code>Duktape</code> 全局对象提供</li>
<li>扩展类型：自定义 "buffer" 和 "pointer" 类型，扩展字符串类型支持任意二进制字符串和非 <a href="http://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane">BMP</a> 字符串（标准 Ecmascript 仅支持16位码点值）</li>
<li>整合引用计数和标记-清除算法(mark-and-sweep)垃圾回收机制，以及终结器和紧急垃圾回收机制（您也可以只使用标记-清除算法机制进行构建）</li>
<li>协程支持</li>
<li>尾调用支持</li>
<li>内置基于调试器协议的调试器框架</li>
<li>内置无平台依赖性的正则表达式引擎</li>
<li>内置无平台依赖性的 Unicode 支持</li>
<li>内置无平台依赖性的数字转化和格式化</li>
<li>自定义 JSON 格式 (JX 和 JC)</li>
<li>以字节码转储(dump)/加载的方式来缓存已编译的函数</li>
</ul><h2 class="sectiontitle" id="introduction.5">目标 <a class="sectionlink" href="#introduction.5">§</a></h2><p><b>一致性</b>.  Ecmascript E5/E5.1 和现实代码实现的一致性。Ecmascript 的一致性需要正则表达式和 Unicode 支持。可能的话，将实现最新的或起草阶段的 Ecmascript 规范中的特性，以最小化 Duktape 自定义特性。</p><p><b>Portability</b>.  Minimal system dependencies are nice when porting,
so Duktape depends on very few system libraries.  For example, number
formatting and parsing, regular expressions, and Unicode are all implemented
internally by Duktape.  One of the few dependencies that cannot be fully
eliminated is system date/time integration in the <code>Date</code> built-in.
Duktape supports major platforms directly but you can also use an external
Date provider on exotic platforms.</p><p><b>Easy C interface</b>.  The interface between Duktape and C programs
should be natural and error-tolerant.  As a particular issue, string
representation should be UTF-8 with automatic NUL terminators to match
common C use.</p><p><b>Small footprint</b>.  Code and data footprint should be as small as
possible, even for small programs.  Duktape is portable even to "bare metal"
targets with no standard libraries.  This is more important than performance,
as there are already several very fast engines but fewer very compact,
portable engines.</p><p><b>Reasonable performance</b>.  Small footprint (and portability, to some
extent) probably eliminates the possibility of a competitive JIT-based engine,
so there is no practical way of competing with very advanced JIT-based engines
like SpiderMonkey (and its optimized variants) or Google V8.  Performance
should still be reasonable for typical embedded programs.
<a href="http://www.lua.org/">Lua</a> is a good benchmark in this respect.
(Adding optional, modular support for JITing or perhaps off-line compilation
would be nice.)</p><p><b>ASCII string performance</b>.  It's important that operations dealing
with plain ASCII strings be very fast: ASCII dominates most embedded use.
Operations dealing with non-ASCII strings need to perform reasonably but are
not critical.  This is a necessary trade-off: using C-compatible strings means
essentially using UTF-8 string representation which makes string indexing and
many other operations slower than with fixed size character representations.
It's still important to support common idioms like iterating strings sequentially
(in either direction) efficiently.</p><h2 class="sectiontitle" id="introduction.6">Document organization <a class="sectionlink" href="#introduction.6">§</a></h2><p><a href="#gettingstarted">Getting started</a> guides you through downloading,
compiling, and integrating Duktape into your program.  It also provides concrete
examples of how you can integrate scripting capabilities into your program.</p><p><a href="#programming">Programming model</a>, <a href="#stacktypes">Stack types</a>,
and <a href="#ctypes">C types</a>
discuss core Duktape concepts such as <i>heap</i>, <i>context</i>, <i>value stacks</i>,
<i>Duktape API</i>, and <i>Duktape/C functions</i>.  Duktape stack types and C type
wrappers are discussed in detail.</p><p>Duktape specific Ecmascript features are discussed in multiple sections:
<a href="#typealgorithms">Type algorithms</a> (for custom types),
<a href="#duktapebuiltins">Duktape built-ins</a> (additional built-ins), 
<a href="#postes5features">Post-ES5 features</a> (features implemented from ES2016 and beyond),
<a href="#custombehavior">Custom behavior</a> (behavior differing from standard),
<a href="#customjson">Custom JSON formats</a>,
<a href="#customdirectives">Custom directives</a>,
<a href="#bufferobjects">Buffer objects</a>,
<a href="#errorobjects">Error objects</a> (properties and traceback support),
<a href="#functionobjects">Function objects</a> (properties),
<a href="#datetime">Date and time</a>,
<a href="#random">Random numbers</a>,
<a href="#debugger">Debugger</a>,
<a href="#modules">Modules</a>,
<a href="#finalization">Finalization</a>,
<a href="#coroutines">Coroutines</a>,
<a href="#virtualproperties">Virtual properties</a>,
<a href="#symbols">Symbols</a>,
<a href="#bytecodedumpload">Bytecode dump/load</a>,
<a href="#threading">Threading</a>,
<a href="#sandboxing">Sandboxing</a>.
</p><p><a href="#performance">Performance</a> provides a few Duktape-specific tips
for improving performance and avoiding performance pitfalls.
<a href="#memoryusage">Memory usage</a> summarizes Duktape memory usage and
gives pointers for minimizing it.
<a href="#compiling">Compiling</a> describes how to configure and compile Duktape
as part of your application.
<a href="#portability">Portability</a> covers platform and compiler specific
issues and other portability issues.
<a href="#compatibility">Compatibility</a> discusses Duktape's compatibility
with Ecmascript dialects, extensions, and frameworks.
<a href="#versioning">Versioning</a> describes Duktape versioning and what version
compatibility to expect.
<a href="#limitations">Limitations</a> summarizes currently known limitations
and provides possible workarounds.</p><p><a href="#comparisontolua">Comparison to Lua</a> discusses some differences
between Lua and Duktape; it may be useful reading if you're already familiar with Lua.</p><hr/><h1 class="sectiontitle" id="gettingstarted">Getting started <a class="sectionlink" href="#gettingstarted">§</a></h1><h2 class="sectiontitle" id="gettingstarted.1">Downloading <a class="sectionlink" href="#gettingstarted.1">§</a></h2><p>Download the source distributable from the
<a href="download.html">Download</a> page.</p><h2 class="sectiontitle" id="gettingstarted.2">Command line tool for testing <a class="sectionlink" href="#gettingstarted.2">§</a></h2><p>Unpack the distributable:</p><pre>
$ cd /tmp
$ tar xvfJ duktape-&lt;version&gt;.tar.xz
</pre><p>Compile the command line tool using the provided Makefile:</p><pre>
$ cd /tmp/duktape-&lt;version&gt;/
$ make -f Makefile.cmdline
</pre><p>The Makefile assumes you have <code>gcc</code> installed.  If you don't,
you can just edit the Makefile to match your compiler (the Makefile is
quite simple).</p><div class="note">
Duktape doesn't provide built-in bindings for file or console I/O to avoid
portability issues (for example, some platforms don't have I/O APIs at all).
The command line utility provides <code>print()</code> and <code>alert()</code>
bindings using <a href="https://github.com/svaarala/duktape/blob/master/extras/print-alert">extras/print-alert</a>
to make it easier to play with.  There are useful "extras" in the distributable
providing useful (optional) bindings such as:
<ul>
<li><a href="https://github.com/svaarala/duktape/blob/master/extras/print-alert">print() and alert()</a></li>
<li><a href="https://github.com/svaarala/duktape/blob/master/extras/console">console object, e.g. console.log()</a></li>
</ul>
<b>Throughout the guide examples will assume a <code>print()</code> binding for
illustration.</b>
</div><div class="note">
The command line tool avoids platform dependencies by default.  You can add
line editing support via <a href="https://github.com/antirez/linenoise">linenoise</a>
by editing the Makefile:
<ul>
<li>Add <code class="nobreak">-DDUK_CMDLINE_FANCY</code></li>
<li>Add <code>-Ipath/to/linenoise</code> for the <code>linenoise.h</code> header</li>
<li>Add <code>path/to/linenoise.c</code> to the source list</li>
<li>Linenoise only works in POSIX environments and requires a C compiler (not C++)</li>
</ul>
</div><p>You can now run Ecmascript code interactively:</p><pre>
$ ./duk
((o) Duktape 2.0.0 (v2.0.0)
duk&gt; print('Hello world!')
Hello world!
= undefined
</pre><p>You can also run Ecmascript code from a file which is useful for playing with
features and algorithms.  As an example, create <code>fib.js</code>:</p><pre class="ecmascript-code"><span class="comment">// fib.js</span>
<span class="keyword">function</span><span class="normal"> </span><span class="function">fib</span><span class="symbol">(</span><span class="normal">n</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="keyword">if</span><span class="normal"> </span><span class="symbol">(</span><span class="normal">n </span><span class="symbol">==</span><span class="normal"> </span><span class="number">0</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span><span class="normal"> </span><span class="keyword">return</span><span class="normal"> </span><span class="number">0</span><span class="symbol">;</span><span class="normal"> </span><span class="cbracket">}</span>
<span class="normal">    </span><span class="keyword">if</span><span class="normal"> </span><span class="symbol">(</span><span class="normal">n </span><span class="symbol">==</span><span class="normal"> </span><span class="number">1</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span><span class="normal"> </span><span class="keyword">return</span><span class="normal"> </span><span class="number">1</span><span class="symbol">;</span><span class="normal"> </span><span class="cbracket">}</span>
<span class="normal">    </span><span class="keyword">return</span><span class="normal"> </span><span class="function">fib</span><span class="symbol">(</span><span class="normal">n</span><span class="symbol">-</span><span class="number">1</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">+</span><span class="normal"> </span><span class="function">fib</span><span class="symbol">(</span><span class="normal">n</span><span class="symbol">-</span><span class="number">2</span><span class="symbol">);</span>
<span class="cbracket">}</span>

<span class="keyword">function</span><span class="normal"> </span><span class="function">test</span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="keyword">var</span><span class="normal"> res </span><span class="symbol">=</span><span class="normal"> </span><span class="symbol">[];</span>
<span class="normal">    </span><span class="keyword">for</span><span class="normal"> </span><span class="symbol">(</span><span class="normal">i </span><span class="symbol">=</span><span class="normal"> </span><span class="number">0</span><span class="symbol">;</span><span class="normal"> i </span><span class="symbol">&lt;</span><span class="normal"> </span><span class="number">20</span><span class="symbol">;</span><span class="normal"> i</span><span class="symbol">++)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">        res</span><span class="symbol">.</span><span class="function">push</span><span class="symbol">(</span><span class="function">fib</span><span class="symbol">(</span><span class="normal">i</span><span class="symbol">));</span>
<span class="normal">    </span><span class="cbracket">}</span>
<span class="normal">    </span><span class="function">print</span><span class="symbol">(</span><span class="normal">res</span><span class="symbol">.</span><span class="function">join</span><span class="symbol">(</span><span class="string">' '</span><span class="symbol">));</span>
<span class="cbracket">}</span>

<span class="function">test</span><span class="symbol">();</span>
</pre><p>Test the script from the command line:</p><pre>
$ ./duk fib.js
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
</pre><h2 class="sectiontitle" id="gettingstarted.3">Integrating Duktape into your program <a class="sectionlink" href="#gettingstarted.3">§</a></h2><p>The command line tool is simply an example of a program which embeds
Duktape.  Embedding Duktape into your program is very simple:</p><ul>
<li>Run <code>duktape-N.N.N/tools/configure.py</code> to configure Duktape
    for build.  The result is a directory containing <code>duktape.c</code>,
    <code>duktape.h</code>, and <code>duk_config.h</code>.</li>
<li>Add <code>duktape.c</code>, <code>duktape.h</code>, and <code>duk_config.h</code>
    to your build, and call the Duktape API from elsewhere in your program.</li>
</ul><p>The Duktape distributable (duktape-N.N.N.tar.xz) <code>src/</code> directory
contains preconfigured header and source files for the Duktape default configuration
which can usually be used as is.  If needed, the configuration tool allows you to customize
Duktape options, such as optimizing Duktape for low memory targets and
enable/disable features.  See <a href="#compiling">Compiling</a> and
<a href="http://wiki.duktape.org/Configuring.html">Configuring Duktape for build</a>
for more details and examples.</p><p>The distributable contains a very simple example program, <code>hello.c</code>,
which illustrates this process.  Compile the test program with the preconfigured
Duktape header and source files e.g. as follows:</p><pre>
$ cd /tmp/duktape-&lt;version&gt;/
$ gcc -std=c99 -o hello -Isrc src/duktape.c examples/hello/hello.c -lm
</pre><p>To customize Duktape configuration use <code>configure.py</code>:</p><pre>
$ cd /tmp/duktape-&lt;version&gt;/
# Here we disable Ecmascript 6 Proxy object support
$ python2 tools/configure.py --output-directory duktape-src -UDUK_USE_ES6_PROXY
$ gcc -std=c99 -o hello -Iduktape-src duktape-src/duktape.c examples/hello/hello.c -lm
</pre><p>The test program creates a Duktape context and uses it to run some
Ecmascript code:</p><pre>
$ ./hello
Hello world!
2+3=5
</pre><p>Because Duktape is an embeddable engine, you don't need to change
the basic control flow of your program.  The basic approach is:</p><ul>
<li>Create a Duktape context e.g. in program initialization
    (or even on-demand when scripting is needed).  Usually you
    would also load your scripts during initialization, though
    that can also be done on-demand.</li>
<li>Identify points in your code where you would like to use scripting
    and insert calls to script functions there.</li>
<li>To make a script function call, first push call arguments to the
    Duktape context's <i>value stack</i> using the Duktape API.
    Then, use another Duktape API call to initiate the actual call.</li>
<li>Once script execution is finished, control is returned to your
    program (the API call returns) and a return value is left on the
    Duktape context's value stack.  C code can then access the return
    value using the Duktape API.</li>
</ul><p>More broadly, there are several approaches to how you can use Duktape
with native code; for example:</p><ul>
<li>Run the main application in C/C++ code but call into Duktape for
    extending base functionality (e.g. plugins or configuration).</li>
<li>Run the main application in Ecmascript code, and call into simple
    C/C++ native bindings for I/O, performance intensive operations, etc.
    The native bindings are often kept stateless so that state logic
    remains in view of script code.</li>
<li>Run the main application in Ecmascript code, but use more complex,
    stateful C/C++ native bindings for performance intensive operations.
    For example, a graphics engine can be implemented as a native object.</li>
</ul><p>See the following Wiki articles for detailed examples:</p><ul>
<li><a href="http://wiki.duktape.org/GettingStartedLineProcessing.html">Getting started: line processing</a></li>
<li><a href="http://wiki.duktape.org/GettingStartedPrimalityTesting.html">Getting started: primality testing</a></li>
</ul><hr/><h1 class="sectiontitle" id="programming">Programming model <a class="sectionlink" href="#programming">§</a></h1><h2 class="sectiontitle" id="programming.1">Overview <a class="sectionlink" href="#programming.1">§</a></h2><p>Programming with Duktape is quite straightforward:</p><ul>
<li>Add Duktape source (<code>duktape.c</code>) and headers
    (<code>duktape.h</code> and <code>duk_config.h</code>)
    to your build.</li>
<li>Create a Duktape <b>heap</b> (a garbage collection region) and an initial
    <b>context</b> (essentially a thread handle) in your program.</li>
<li>Load the necessary Ecmascript script files, and register your Duktape/C
    functions.  Duktape/C functions are C functions you can call from
    Ecmascript code for better performance, bindings to native libraries, etc.</li>
<li>Use the Duktape API to call Ecmascript functions whenever appropriate.
    Duktape API is used to pass values to and from functions.  Values are
    converted between their C representation and the Duktape internal
    (Ecmascript compatible) representation.</li>
<li>Duktape API is also used by Duktape/C functions (called from Ecmascript)
    to access call arguments and to provide return values.</li>
</ul><p>Let's look at all the steps and their related concepts in more detail.</p><h2 class="sectiontitle" id="programming.2">Heap and context <a class="sectionlink" href="#programming.2">§</a></h2><p>A Duktape <b>heap</b> is a single region for garbage collection.  A heap
is used to allocate storage for strings, Ecmascript objects, and other
variable size, garbage collected data.  Objects in the heap have an internal
heap header which provides the necessary information for reference counting,
mark-and-sweep garbage collection, object finalization, etc.
Heap objects can reference each other, creating a reachability graph from
a garbage collection perspective.  For instance, the properties of an Ecmascript
object reference both the keys and values of the object's property set.  You can
have multiple heaps, but objects in different heaps cannot reference each other
directly; you need to use serialization to pass values between heaps.</p><p>A Duktape <b>context</b> is an Ecmascript "thread of execution" which lives
in a certain Duktape heap.  A context is represented by a <code>duk_context *</code>
in the Duktape API, and is associated with an internal Duktape coroutine (a form
of a co-operative thread).  Each context is also associated with an environment
consisting of global objects; contexts may share the same global environment but
can also have different environments.  The context handle is given to almost every
Duktape API call, and allows the caller to interact with the <b>value stack</b> of
the Duktape coroutine: values can be inserted and queries, functions can be called,
and so on.</p><p>Each coroutine has a <b>call stack</b> which controls execution, keeping
track of function calls, native or Ecmascript, within the Ecmascript engine.
Each coroutine also has a <b>value stack</b> which stores all the Ecmascript
values of the coroutine's active call stack.  The value stack always has an
active <b>stack frame</b> for the most recent function call (when no function
calls have been made, the active stack frame is the value stack as is).
The Duktape API calls operate almost exclusively in the currently active
stack frame.  A coroutine also has an internal <b>catch stack</b> which is used
to track error catching sites established using e.g. <code>try-catch-finally</code>
blocks.  This is not visible to the caller in any way at the moment.</p><p>Multiple contexts can share the same Duktape <b>heap</b>.  In more concrete
terms this means that multiple contexts can share the same garbage collection
state, and can exchange object references safely.  Contexts in different heaps
cannot exchange direct object references; all values must be serialized in one
way or another.</p><p>Almost every API call provided by the Duktape API takes a context pointer
as its first argument: no global variables or states are used, and there are
no restrictions on running multiple, independent Duktape heaps and contexts
at the same time.  There are multi-threading restrictions, however: only one
native thread can execute any code within a single heap at any time, see
<a href="#threading">Threading</a>.</p><p>To create a Duktape heap and an initial context inside the heap, you can
simply use:</p><pre class="c-code"><span class="usertype">duk_context</span><span class="normal"> </span><span class="symbol">*</span><span class="normal">ctx </span><span class="symbol">=</span><span class="normal"> </span><span class="function">duk_create_heap_default</span><span class="symbol">();</span>
<span class="keyword">if</span><span class="normal"> </span><span class="symbol">(!</span><span class="normal">ctx</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span><span class="normal"> </span><span class="function">exit</span><span class="symbol">(</span><span class="number">1</span><span class="symbol">);</span><span class="normal"> </span><span class="cbracket">}</span>
</pre><p>If you wish to provide your own memory allocation functions and a fatal
error handler function (recommended), use:</p><pre class="c-code"><span class="usertype">duk_context</span><span class="normal"> </span><span class="symbol">*</span><span class="normal">ctx </span><span class="symbol">=</span><span class="normal"> </span><span class="function">duk_create_heap</span><span class="symbol">(</span><span class="normal">my_alloc</span><span class="symbol">,</span>
<span class="normal">                                   my_realloc</span><span class="symbol">,</span>
<span class="normal">                                   my_free</span><span class="symbol">,</span>
<span class="normal">                                   my_udata</span><span class="symbol">,</span>
<span class="normal">                                   my_fatal</span><span class="symbol">);</span>
<span class="keyword">if</span><span class="normal"> </span><span class="symbol">(!</span><span class="normal">ctx</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span><span class="normal"> </span><span class="function">exit</span><span class="symbol">(</span><span class="number">1</span><span class="symbol">);</span><span class="normal"> </span><span class="cbracket">}</span>
</pre><p>To create a new context inside the same heap, with the context sharing the
same global objects:</p><pre class="c-code"><span class="usertype">duk_context</span><span class="normal"> </span><span class="symbol">*</span><span class="normal">new_ctx</span><span class="symbol">;</span>

<span class="symbol">(</span><span class="type">void</span><span class="symbol">)</span><span class="normal"> </span><span class="function">duk_push_thread</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">);</span>
<span class="normal">new_ctx </span><span class="symbol">=</span><span class="normal"> </span><span class="function">duk_get_context</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">-</span><span class="number">1</span><span class="normal"> </span><span class="comment">/*index*/</span><span class="symbol">);</span>
</pre><p>To create a new context inside the same heap, but with a fresh set of global
object:</p><pre class="c-code"><span class="usertype">duk_context</span><span class="normal"> </span><span class="symbol">*</span><span class="normal">new_ctx</span><span class="symbol">;</span>

<span class="symbol">(</span><span class="type">void</span><span class="symbol">)</span><span class="normal"> </span><span class="function">duk_push_thread_new_globalenv</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">);</span>
<span class="normal">new_ctx </span><span class="symbol">=</span><span class="normal"> </span><span class="function">duk_get_context</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">-</span><span class="number">1</span><span class="normal"> </span><span class="comment">/*index*/</span><span class="symbol">);</span>
</pre><p>Contexts are automatically garbage collected when they become unreachable.
This also means that if your C code holds a <code>duk_context *</code>, the
corresponding Duktape coroutine MUST be reachable from a garbage collection
point of view.</p><p>A heap must be destroyed explicitly when the caller is done with it:</p><pre class="c-code"><span class="function">duk_destroy_heap</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">);</span>
</pre><p>This frees all heap objects allocated, and invalidates any pointers to
such objects.  In particular, if the calling program holds string pointers
to values which resided on the value stack of a context associated with the
heap, such pointers are invalidated and must never be dereferenced after
the heap destruction call returns.</p><h2 class="sectiontitle" id="programming.3">Call stack and catch stack (of a context) <a class="sectionlink" href="#programming.3">§</a></h2><p>The call stack of a context is not directly visible to the caller.
It keeps track of the chain of function calls, either C or Ecmascript,
currently executing in a context.  The main purpose of this book-keeping is
to facilitate the passing of arguments and results between function callers
and callees, and to keep track of how the value stack is divided between
function calls.  The call stack also allows Duktape to construct a traceback
for errors.</p><p>Closely related to the call stack, Duktape also maintains a catch stack
for keeping track of current error catching sites established using e.g.
<code>try-catch-finally</code>.  The catch stack is even less visible to the
caller than the call stack.</p><p>Because Duktape supports tail calls, the call stack does not always
accurately represent the true call chain: tail calls will be "squashed"
together in the call stack.</p><div class="note">Don't confuse with the C stack.</div><h2 class="sectiontitle" id="programming.4">Value stack (of a context) and value stack index <a class="sectionlink" href="#programming.4">§</a></h2><p>The value stack of a context is an array of tagged type values related
to the current execution state of a coroutine.  The tagged types used are:
<code>undefined</code>, <code>null</code>, boolean, number, string, object,
buffer, pointer, and lightfunc.  For a detailed discussion of the available
tagged types, see <a href="#stacktypes">Types</a>.</p><p>The value stack is divided between the currently active function calls
(activations) on the coroutine's call stack.  At any time, there is an active
stack frame which provides an origin for indexing elements on the stack.
More concretely, at any time there is a <b>bottom</b> which is referred
to with the index zero in the Duktape API.  There is also a conceptual
<b>top</b> which identifies the stack element right above the highest
currently used element.  The following diagram illustrates this:</p><pre>
 Value stack
 of 15 entries
 (absolute indices)

.----.
| 15 |
| 14 |
| 13 |
| 12 |      Active stack frame (indices
| 11 |      relative to stack bottom)
| 10 |
|  9 |      .---.
|  8 |      | 5 |   API index 0 is bottom (at value stack index 3).
|  7 |      | 4 |
|  6 |      | 3 |   API index 5 is highest used (at value stack index 8).
|  5 |      | 2 |   
|  4 |      | 1 |   Stack top is 6 (relative to stack bottom).
|  3 | &lt;--- | 0 |
|  2 |      `---'
|  1 |
|  0 |
`----'
</pre><p>There is no direct way to refer to elements in the internal value stack:
Duktape API always deals with the currently active stack frame.  Stack frames
are shown horizontally throughout the documentation for space reasons.  For
example, the active stack frame in the figure above would be shown as:</p><div class="stack-wrapper"> <span class="stack"> <span class="cap">[</span> <span class="elem">0</span> <span class="elem">1</span> <span class="elem">2</span> <span class="elem">3</span> <span class="elem">4</span> <span class="elem">5</span> <span class="cap">]</span> </span> <span class="stack-comment"></span> </div><p>A <b>value stack index</b> is a signed integer index used in the Duktape
API to refer to elements in currently active stack frame, relative to the
current frame bottom.</p><p>Non-negative (&gt;= 0) indices refer to stack entries in the
current stack frame, relative to the frame bottom:</p><div class="stack-wrapper"> <span class="stack"> <span class="cap">[</span> <span class="elem">0</span> <span class="elem">1</span> <span class="elem">2</span> <span class="elem">3</span> <span class="elem">4</span> <span class="elem active">5</span> <span class="cap">]</span> </span> <span class="stack-comment"></span> </div><p>Negative (&lt; 0) indices refer to stack entries relative to the top:</p><div class="stack-wrapper"> <span class="stack"> <span class="cap">[</span> <span class="elem">-6</span> <span class="elem">-5</span> <span class="elem">-4</span> <span class="elem">-3</span> <span class="elem">-2</span> <span class="elem active">-1</span> <span class="cap">]</span> </span> <span class="stack-comment"></span> </div><p>The special constant <code>DUK_INVALID_INDEX</code> is a negative integer
which denotes an invalid stack index.  It can be returned from API calls
and can also be given to API calls to indicate a "no value".</p><p>The <b>value stack top</b> (or just "top") is the non-negative index of
an imaginary element just above the highest used index.  For instance, above
the highest used index is 5, so the stack top is 6.  The top indicates the
current stack size, and is also the index of the next element pushed to the
stack.</p><div class="stack-wrapper"> <span class="stack"> <span class="cap">[</span> <span class="elem">0</span> <span class="elem">1</span> <span class="elem">2</span> <span class="elem">3</span> <span class="elem">4</span> <span class="elem active">5</span> <span class="elem ghost">6</span> <span class="cap">]</span> </span> <span class="stack-comment"></span> </div><div class="note">
<p>API stack operations are always confined to the current stack frame.
There is no way to refer to stack entries below the current frame.  This
is intentional, as it protects functions in the call stack from affecting
each other's values.</p>
</div><div class="note">Don't confuse with the C stack.</div><h2 class="sectiontitle" id="programming.5">Growing the value stack <a class="sectionlink" href="#programming.5">§</a></h2><p>At any time, the value stack of a context is allocated for a certain
maximum number of entries.  An attempt to push values beyond the allocated
size will cause an error to be thrown, it will <b>not</b> cause the value
stack to be automatically extended.  This simplifies the internal
implementation and also improves performance by minimizing reallocations
when you know, beforehand, that a certain number of entries will be needed
during a function.</p><p>When a value stack is created or a Duktape/C function is entered, the
value stack is always guaranteed to have space for the call arguments and
<code>DUK_API_ENTRY_STACK</code> (currently 64) elements.  In the typical
case this is more than sufficient so that the majority of Duktape/C
functions don't need to extend the value stack.  Only functions that need
more space or perhaps need an input-dependent amount of space need to grow
the value stack.</p><p>You can extend the stack allocation explicitly with
<code><a href="api.html#duk_check_stack">duk_check_stack()</a></code>
or (usually more preferably)
<code><a href="api.html#duk_require_stack">duk_require_stack()</a></code>.
Once successfully
extended, you are again guaranteed that the specified number of elements can
be pushed to the stack.  There is no way to shrink the allocation except by
returning from a Duktape/C function.</p><p>Consider, for instance, the following function which will uppercase an
input ASCII string by pushing uppercased characters one-by-one on the stack
and then concatenating the result.  This example illustrates how the number
of value stack entries required may depend on the input (otherwise this is
not a very good approach for uppercasing a string):</p><pre class="c-code"><span class="comment">/* uppercase.c */</span>
<span class="preproc">#include</span><span class="normal"> </span><span class="string">&lt;stdio.h&gt;</span>
<span class="preproc">#include</span><span class="normal"> </span><span class="string">&lt;stdlib.h&gt;</span>
<span class="preproc">#include</span><span class="normal"> </span><span class="string">"duktape.h"</span>

<span class="keyword">static</span><span class="normal"> </span><span class="type">int</span><span class="normal"> </span><span class="function">dummy_upper_case</span><span class="symbol">(</span><span class="usertype">duk_context</span><span class="normal"> </span><span class="symbol">*</span><span class="normal">ctx</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="usertype">size_t</span><span class="normal"> sz</span><span class="symbol">;</span>
<span class="normal">    </span><span class="keyword">const</span><span class="normal"> </span><span class="type">char</span><span class="normal"> </span><span class="symbol">*</span><span class="normal">val </span><span class="symbol">=</span><span class="normal"> </span><span class="function">duk_require_lstring</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="number">0</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">&amp;</span><span class="normal">sz</span><span class="symbol">);</span>
<span class="normal">    </span><span class="usertype">size_t</span><span class="normal"> i</span><span class="symbol">;</span>

<span class="normal">    </span><span class="comment">/* We're going to need 'sz' additional entries on the stack. */</span>
<span class="normal">    </span><span class="function">duk_require_stack</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> sz</span><span class="symbol">);</span>

<span class="normal">    </span><span class="keyword">for</span><span class="normal"> </span><span class="symbol">(</span><span class="normal">i </span><span class="symbol">=</span><span class="normal"> </span><span class="number">0</span><span class="symbol">;</span><span class="normal"> i </span><span class="symbol">&lt;</span><span class="normal"> sz</span><span class="symbol">;</span><span class="normal"> i</span><span class="symbol">++)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">        </span><span class="type">char</span><span class="normal"> ch </span><span class="symbol">=</span><span class="normal"> val</span><span class="symbol">[</span><span class="normal">i</span><span class="symbol">];</span>
<span class="normal">        </span><span class="keyword">if</span><span class="normal"> </span><span class="symbol">(</span><span class="normal">ch </span><span class="symbol">&gt;=</span><span class="normal"> </span><span class="string">'a'</span><span class="normal"> </span><span class="symbol">&amp;&amp;</span><span class="normal"> ch </span><span class="symbol">&lt;=</span><span class="normal"> </span><span class="string">'z'</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">            ch </span><span class="symbol">=</span><span class="normal"> ch </span><span class="symbol">-</span><span class="normal"> </span><span class="string">'a'</span><span class="normal"> </span><span class="symbol">+</span><span class="normal"> </span><span class="string">'A'</span><span class="symbol">;</span>
<span class="normal">        </span><span class="cbracket">}</span>
<span class="normal">        </span><span class="function">duk_push_lstring</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">(</span><span class="keyword">const</span><span class="normal"> </span><span class="type">char</span><span class="normal"> </span><span class="symbol">*)</span><span class="normal"> </span><span class="symbol">&amp;</span><span class="normal">ch</span><span class="symbol">,</span><span class="normal"> </span><span class="number">1</span><span class="symbol">);</span>
<span class="normal">    </span><span class="cbracket">}</span>

<span class="normal">    </span><span class="function">duk_concat</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> sz</span><span class="symbol">);</span>
<span class="normal">    </span><span class="keyword">return</span><span class="normal"> </span><span class="number">1</span><span class="symbol">;</span>
<span class="cbracket">}</span>

<span class="type">int</span><span class="normal"> </span><span class="function">main</span><span class="symbol">(</span><span class="type">int</span><span class="normal"> argc</span><span class="symbol">,</span><span class="normal"> </span><span class="type">char</span><span class="normal"> </span><span class="symbol">*</span><span class="normal">argv</span><span class="symbol">[])</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="usertype">duk_context</span><span class="normal"> </span><span class="symbol">*</span><span class="normal">ctx</span><span class="symbol">;</span>

<span class="normal">    </span><span class="keyword">if</span><span class="normal"> </span><span class="symbol">(</span><span class="normal">argc </span><span class="symbol">&lt;</span><span class="normal"> </span><span class="number">2</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span><span class="normal"> </span><span class="function">exit</span><span class="symbol">(</span><span class="number">1</span><span class="symbol">);</span><span class="normal"> </span><span class="cbracket">}</span>

<span class="normal">    ctx </span><span class="symbol">=</span><span class="normal"> </span><span class="function">duk_create_heap_default</span><span class="symbol">();</span>
<span class="normal">    </span><span class="keyword">if</span><span class="normal"> </span><span class="symbol">(!</span><span class="normal">ctx</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span><span class="normal"> </span><span class="function">exit</span><span class="symbol">(</span><span class="number">1</span><span class="symbol">);</span><span class="normal"> </span><span class="cbracket">}</span>

<span class="normal">    </span><span class="function">duk_push_c_function</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> dummy_upper_case</span><span class="symbol">,</span><span class="normal"> </span><span class="number">1</span><span class="symbol">);</span>
<span class="normal">    </span><span class="function">duk_push_string</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> argv</span><span class="symbol">[</span><span class="number">1</span><span class="symbol">]);</span>
<span class="normal">    </span><span class="function">duk_call</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="number">1</span><span class="symbol">);</span>
<span class="normal">    </span><span class="function">printf</span><span class="symbol">(</span><span class="string">"%s -&gt; %s</span><span class="specialchar">\n</span><span class="string">"</span><span class="symbol">,</span><span class="normal"> argv</span><span class="symbol">[</span><span class="number">1</span><span class="symbol">],</span><span class="normal"> </span><span class="function">duk_to_string</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">-</span><span class="number">1</span><span class="symbol">));</span>
<span class="normal">    </span><span class="function">duk_pop</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">);</span>

<span class="normal">    </span><span class="function">duk_destroy_heap</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">);</span>
<span class="normal">    </span><span class="keyword">return</span><span class="normal"> </span><span class="number">0</span><span class="symbol">;</span>
<span class="cbracket">}</span>
</pre><p>In addition to user reserved elements, Duktape keeps an automatic internal
value stack reserve to ensure all API calls have enough value stack space to
work without further allocations.  The value stack is also extended and shrunk
in somewhat large steps to minimize memory reallocation activity.  As a result
the internal number of value stack elements available beyond the caller
specified extra varies considerably.  The caller does not need to take this
into account and should never rely on any additional elements being available.</p><h2 class="sectiontitle" id="programming.6">Ecmascript array index <a class="sectionlink" href="#programming.6">§</a></h2><p>Ecmascript object and array keys can only be strings.  Array indices
(e.g. 0, 1, 2) are represented as canonical string representations of the
respective numbers.  More technically, all canonical string representations
of the integers in the range [0, 2**32-1] are valid array indices.</p><p>To illustrate the Ecmascript array index handling, consider the following
example:</p><pre class="ecmascript-code"><span class="keyword">var</span><span class="normal"> arr </span><span class="symbol">=</span><span class="normal"> </span><span class="symbol">[</span><span class="normal"> </span><span class="string">'foo'</span><span class="symbol">,</span><span class="normal"> </span><span class="string">'bar'</span><span class="symbol">,</span><span class="normal"> </span><span class="string">'quux'</span><span class="normal"> </span><span class="symbol">];</span>

<span class="function">print</span><span class="symbol">(</span><span class="normal">arr</span><span class="symbol">[</span><span class="number">1</span><span class="symbol">]);</span><span class="normal">     </span><span class="comment">// refers to 'bar'</span>
<span class="function">print</span><span class="symbol">(</span><span class="normal">arr</span><span class="symbol">[</span><span class="string">"1"</span><span class="symbol">]);</span><span class="normal">   </span><span class="comment">// refers to 'bar'</span>

<span class="function">print</span><span class="symbol">(</span><span class="normal">arr</span><span class="symbol">[</span><span class="number">1.0</span><span class="symbol">]);</span><span class="normal">   </span><span class="comment">// refers to 'bar', canonical encoding is "1"</span>
<span class="function">print</span><span class="symbol">(</span><span class="normal">arr</span><span class="symbol">[</span><span class="string">"1.0"</span><span class="symbol">]);</span><span class="normal"> </span><span class="comment">// undefined, not an array index</span>
</pre><p>Some API calls operating on Ecmascript arrays accept numeric array index
arguments.  This is really just a short hand for denoting a string conversion
of that number.  For instance, if the API is given the integer 123, this
really refers to the property name "123".</p><p>Internally, Duktape tries to avoid converting numeric indices to actual
strings whenever possible, so it is preferable to use array index API calls
when they are relevant.  Similarly, when writing Ecmascript code it is
preferable to use numeric rather than string indices, as the same fast path
applies for Ecmascript code.</p><h2 class="sectiontitle" id="duktape-api">Duktape API <a class="sectionlink" href="#duktape-api">§</a></h2><p>Duktape API is the collection of user callable API calls defined in
<code>duktape.h</code> and documented in the
<a href="api.html">API reference</a>.</p><p>The Duktape API calls are generally error tolerant and will check all
arguments for errors (such as <code>NULL</code> pointers).  However, to
minimize footprint, the <code>ctx</code> argument is not checked, and the
caller MUST NOT call any Duktape API calls with a <code>NULL</code> context.</p><p>All Duktape API calls are potentially macros.  Calling code must not rely
on any Duktape API call being available as a function pointer.  The
implementation of a certain API call may change between a macro and an
actual function even between compatible releases.  The Duktape API provides
the following guarantees for macros:</p><ul>
<li>Arguments are never evaluated more than once (unless explicitly mentioned).
    However, an argument may not be evaluated at all if an argument is ignored
    in the current version.</li>
<li>An API call with a return value can be used as an expression.  If the API
    macro contains multiple statements, it is implemented as a comma expression
    (e.g. <code>(foo, bar, quux)</code>).</li>
<li>An API call with a <code>void</code> return value may not necessarily work
    as part of an expression.  The API macro may be implemented as a block
    statement or as a dummy <code>do {...} while (0)</code> loop.</li>
</ul><h2 class="sectiontitle" id="programming.8">Duktape/C function <a class="sectionlink" href="#programming.8">§</a></h2><p>A C function with a Duktape/C API signature can be associated with an
Ecmascript function object, and gets called when the Ecmascript function
object is called.  A Duktape/C API function looks as follows:</p><pre class="c-code"><span class="usertype">duk_ret_t</span><span class="normal"> </span><span class="function">my_func</span><span class="symbol">(</span><span class="usertype">duk_context</span><span class="normal"> </span><span class="symbol">*</span><span class="normal">ctx</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="function">duk_push_int</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="number">123</span><span class="symbol">);</span>
<span class="normal">    </span><span class="keyword">return</span><span class="normal"> </span><span class="number">1</span><span class="symbol">;</span>
<span class="cbracket">}</span>
</pre><p>The function gets Ecmascript call argument in the value stack of
<code>ctx</code>, with
<code><a href="api.html#duk_get_top">duk_get_top()</a></code>
indicating the number of
arguments present on the value stack.  The <code>this</code> binding is not
automatically pushed to the value stack; use
<code><a href="api.html#duk_push_this">duk_push_this()</a></code>
to access it.  When creating an Ecmascript function object associated with a
Duktape/C function, one can select the desired number of arguments.  Extra
arguments are dropped and missing arguments are replaced with
<code>undefined</code>.  A function can also be registered as a vararg
function (by giving <code>DUK_VARARGS</code> as the argument count) in
which case call arguments are not modified prior to C function entry.</p><p>The function can return one of the following:</p><ul>
<li>Return value 1 indicates that the value on the stack top is to be
    interpreted as a return value.</li>
<li>Return value 0 indicates that there is no explicit return value on
    the value stack; an <code>undefined</code> is returned to caller.</li>
<li>A negative return value indicates that an error is to be automatically
    thrown.  Error codes named <code>DUK_RET_xxx</code> map to specific kinds
    of errors (do not confuse these with <code>DUK_ERR_xxx</code> which are
    positive values).</li>
<li>A return value higher than 1 is currently undefined, as Ecmascript
    doesn't support multiple return values in Edition 5.1.  (Values higher
    than 1 may be taken into to support multiple return values in Ecmascript
    Edition 6.)</li>
</ul><p>A negative error return value is intended to simplify common error
handling, and is an alternative to constructing and throwing an error
explicitly with Duktape API calls.  No error message can be given; a
message is automatically constructed by Duktape.  For example:</p><pre class="c-code"><span class="usertype">duk_ret_t</span><span class="normal"> </span><span class="function">my_func</span><span class="symbol">(</span><span class="usertype">duk_context</span><span class="normal"> </span><span class="symbol">*</span><span class="normal">ctx</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="keyword">if</span><span class="normal"> </span><span class="symbol">(</span><span class="function">duk_get_top</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">==</span><span class="normal"> </span><span class="number">0</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">        </span><span class="comment">/* throw TypeError if no arguments given */</span>
<span class="normal">        </span><span class="keyword">return</span><span class="normal"> DUK_RET_TYPE_ERROR</span><span class="symbol">;</span>
<span class="normal">    </span><span class="cbracket">}</span>
<span class="normal">    </span><span class="comment">/* ... */</span>
<span class="cbracket">}</span>
</pre><p>All Duktape/C functions are considered <b>strict</b> in the
<a href="http://www.ecma-international.org/ecma-262/5.1/#sec-4.2.2">Ecmascript sense</a>.
Duktape API calls always obey Ecmascript strict mode semantics, even when the API calls
are made outside of any Duktape/C function, i.e. with an empty call stack.
For instance, attempt to delete a non-configurable property using
<code><a href="api.html#duk_del_prop">duk_del_prop()</a></code>
will cause an error to be thrown.  This is the case with a strict Ecmascript function too:</p><pre class="ecmascript-code"><span class="keyword">function</span><span class="normal"> </span><span class="function">f</span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="string">'use strict'</span><span class="symbol">;</span>
<span class="normal">    </span><span class="keyword">var</span><span class="normal"> arr </span><span class="symbol">=</span><span class="normal"> </span><span class="symbol">[</span><span class="number">1</span><span class="symbol">,</span><span class="normal"> </span><span class="number">2</span><span class="symbol">,</span><span class="normal"> </span><span class="number">3</span><span class="symbol">];</span>
<span class="normal">    </span><span class="keyword">return</span><span class="normal"> </span><span class="keyword">delete</span><span class="normal"> arr</span><span class="symbol">.</span><span class="normal">length</span><span class="symbol">;</span><span class="normal">  </span><span class="comment">// array 'length' is non-configurable</span>
<span class="cbracket">}</span>

<span class="function">print</span><span class="symbol">(</span><span class="function">f</span><span class="symbol">());</span><span class="normal">  </span><span class="comment">// this throws an error because f() is strict</span>
</pre><p>Another consequence of Duktape/C function strictness is that the <code>this</code>
binding given to Duktape/C functions is not
<a href="http://www.ecma-international.org/ecma-262/5.1/#sec-10.4.3">coerced</a>.
This is also the case for strict Ecmascript code:</p><pre class="ecmascript-code"><span class="keyword">function</span><span class="normal"> </span><span class="function">strictFunc</span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span><span class="normal"> </span><span class="string">'use strict'</span><span class="symbol">;</span><span class="normal"> </span><span class="function">print</span><span class="symbol">(</span><span class="keyword">typeof</span><span class="normal"> </span><span class="keyword">this</span><span class="symbol">);</span><span class="normal"> </span><span class="cbracket">}</span>
<span class="keyword">function</span><span class="normal"> </span><span class="function">nonStrictFunc</span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span><span class="normal"> </span><span class="function">print</span><span class="symbol">(</span><span class="keyword">typeof</span><span class="normal"> </span><span class="keyword">this</span><span class="symbol">);</span><span class="normal"> </span><span class="cbracket">}</span>

<span class="normal">strictFunc</span><span class="symbol">.</span><span class="function">call</span><span class="symbol">(</span><span class="string">'foo'</span><span class="symbol">);</span><span class="normal">     </span><span class="comment">// prints 'string' (uncoerced)</span>
<span class="normal">nonStrictFunc</span><span class="symbol">.</span><span class="function">call</span><span class="symbol">(</span><span class="string">'foo'</span><span class="symbol">);</span><span class="normal">  </span><span class="comment">// prints 'object' (coerced)</span>
</pre><p>Duktape/C functions are currently always <b>constructable</b>, i.e. they
can always be used in <code>new Foo()</code> expressions.  You can check whether
a function was called in constructor mode as follows:</p><pre class="c-code"><span class="keyword">static</span><span class="normal"> </span><span class="usertype">duk_ret_t</span><span class="normal"> </span><span class="function">my_func</span><span class="symbol">(</span><span class="usertype">duk_context</span><span class="normal"> </span><span class="symbol">*</span><span class="normal">ctx</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="keyword">if</span><span class="normal"> </span><span class="symbol">(</span><span class="function">duk_is_constructor_call</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">))</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">        </span><span class="function">printf</span><span class="symbol">(</span><span class="string">"called as a constructor</span><span class="specialchar">\n</span><span class="string">"</span><span class="symbol">);</span>
<span class="normal">    </span><span class="cbracket">}</span><span class="normal"> </span><span class="keyword">else</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">        </span><span class="function">printf</span><span class="symbol">(</span><span class="string">"called as a function</span><span class="specialchar">\n</span><span class="string">"</span><span class="symbol">);</span>
<span class="normal">    </span><span class="cbracket">}</span>
<span class="cbracket">}</span>
</pre><p>To save memory, Duktape/C functions don't have a <code>prototype</code>
property by default, so the default object instance (given to the constructor
as <code>this</code>) inherits from <code>Object.prototype</code>.  To use a
custom prototype you can define <code>prototype</code> for the Duktape/C
function explicitly.  Another approach is to ignore the default object instance
and construct one manually within the Duktape/C call: as with Ecmascript
functions, if a constructor returns an object value, that value replaces the
default object instance and becomes the value of the <code>new</code>
expression.</p><div class="note">
The <code>this</code> binding is not automatically pushed to the value stack;
use
<code><a href="api.html#duk_push_this">duk_push_this()</a></code>
to access it.
</div><h2 class="sectiontitle" id="programming.9">Storing state for a Duktape/C function <a class="sectionlink" href="#programming.9">§</a></h2><p>Sometimes it would be nice to provide parameters or additional state
to a Duktape/C function out-of-band, i.e. outside explicit call arguments.
There are several ways to achieve this.</p><h3 class="sectiontitle" id="programming.9.1">Properties of function <a class="sectionlink" href="#programming.9.1">§</a></h3><p>First, a Duktape/C function can use its Function object to store state
or parameters.  A certain Duktape/C function (the actual C function)
is always represented by an Ecmascript Function object which is
internally associated with the underlying C function.   The Function
object can be used to store properties related to that particular
instance of the function.  Note that a certain Duktape/C function can
be associated with multiple independent Function objects and thus
independent states.</p><p>Accessing the Ecmascript Function object related to a Duktape/C function
is easy:</p><pre class="c-code"><span class="function">duk_push_current_function</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">);</span>
<span class="function">duk_get_prop_string</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">-</span><span class="number">1</span><span class="symbol">,</span><span class="normal"> </span><span class="string">"my_state_variable"</span><span class="symbol">);</span>
</pre><h3 class="sectiontitle" id="programming.9.2">'this' binding <a class="sectionlink" href="#programming.9.2">§</a></h3><p>Another alternative for storing state is to call the Duktape/C function
as a method and then use the <code>this</code> binding for storing state.  For
instance, consider a Duktape/C function called as:</p><pre class="ecmascript-code"><span class="normal">foo</span><span class="symbol">.</span><span class="function">my_c_func</span><span class="symbol">()</span>
</pre><p>When called, the Duktape/C function gets <code>foo</code> as its <code>this</code>
binding, and one could store state directly in <code>foo</code>.  The difference
to using the Function object approach is that the same object is shared by all
methods, which has both advantages and disadvantages.</p><p>Accessing the <code>this</code> binding is easy:</p><pre class="c-code"><span class="function">duk_push_this</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">);</span>
<span class="function">duk_get_prop_string</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">-</span><span class="number">1</span><span class="symbol">,</span><span class="normal"> </span><span class="string">"my_state_variable"</span><span class="symbol">);</span>
</pre><h3 class="sectiontitle" id="programming.9.3">Magic value of function <a class="sectionlink" href="#programming.9.3">§</a></h3><p>Duktape/C function objects can store an internal 16-bit signed integer "magic"
value (zero by default) with no extra memory cost.  The magic value can be used
to pass flags and/or small values to a Duktape/C function at minimal cost, so
that a single native function can provide slightly varied behavior for multiple
function objects:</p><pre class="c-code"><span class="comment">/* Magic value example: two lowest bits are used for a prefix index, bit 2 (0x04)</span>
<span class="comment"> * is used to select newline style for a log write helper.</span>
<span class="comment"> */</span>
<span class="keyword">const</span><span class="normal"> </span><span class="type">char</span><span class="normal"> </span><span class="symbol">*</span><span class="normal">prefix</span><span class="symbol">[</span><span class="number">4</span><span class="symbol">]</span><span class="normal"> </span><span class="symbol">=</span><span class="normal"> </span><span class="cbracket">{</span><span class="normal"> </span><span class="string">"INFO"</span><span class="symbol">,</span><span class="normal"> </span><span class="string">"WARN"</span><span class="symbol">,</span><span class="normal"> </span><span class="string">"ERROR"</span><span class="symbol">,</span><span class="normal"> </span><span class="string">"FATAL"</span><span class="normal"> </span><span class="cbracket">}</span><span class="symbol">;</span>
<span class="usertype">duk_int_t</span><span class="normal"> magic </span><span class="symbol">=</span><span class="normal"> </span><span class="function">duk_get_current_magic</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">);</span>

<span class="function">printf</span><span class="symbol">(</span><span class="string">"%s: %s"</span><span class="symbol">,</span><span class="normal"> prefix</span><span class="symbol">[</span><span class="normal">magic </span><span class="symbol">&amp;</span><span class="normal"> </span><span class="number">0x03</span><span class="symbol">],</span><span class="normal"> </span><span class="function">duk_safe_to_string</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="number">0</span><span class="symbol">));</span>
<span class="keyword">if</span><span class="normal"> </span><span class="symbol">(</span><span class="normal">magic </span><span class="symbol">&amp;</span><span class="normal"> </span><span class="number">0x04</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="function">printf</span><span class="symbol">(</span><span class="string">"</span><span class="specialchar">\r\n</span><span class="string">"</span><span class="symbol">);</span>
<span class="cbracket">}</span><span class="normal"> </span><span class="keyword">else</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="function">printf</span><span class="symbol">(</span><span class="string">"</span><span class="specialchar">\n</span><span class="string">"</span><span class="symbol">);</span>
<span class="cbracket">}</span>
</pre><p>For an API usage example, see the test case
<a href="https://github.com/svaarala/duktape/blob/master/tests/api/test-get-set-magic.c">test-get-set-magic.c</a>.
Duktape uses magic values a lot internally to minimize size of compiled code, see e.g.
<a href="https://github.com/svaarala/duktape/blob/master/src-input/duk_bi_math.c">duk_bi_math.c</a>.</p><div class="note">
The magic value mechanism is liable to change between major Duktape versions,
as the number of available spare bits changes.  Use magic values only when it
really matters for footprint.  Properties stored on the function object is a
more stable alternative.
</div><h3 class="sectiontitle" id="programming.9.4">Heap stash <a class="sectionlink" href="#programming.9.4">§</a></h3><p>The heap stash is an object visible only from C code.  It is associated
with the Duktape heap, and allows Duktape/C code to store "under the hood"
state data which is not exposed to Ecmascript code.  It is accessed with the
<code><a href="api.html#duk_push_heap_stash">duk_push_heap_stash()</a></code>
API call.</p><h3 class="sectiontitle" id="programming.9.5">Global stash <a class="sectionlink" href="#programming.9.5">§</a></h3><p>The global stash is like the heap stash, but is associated with a global
object.  It is accessed with the
<code><a href="api.html#duk_push_global_stash">duk_push_global_stash()</a></code>
API call.  There can be several environments with different global objects
within the same heap.</p><h3 class="sectiontitle" id="programming.9.6">Thread stash <a class="sectionlink" href="#programming.9.6">§</a></h3><p>The thread stash is like the heap stash, but is associated with a Duktape
thread (i.e. a <code>ctx</code> pointer).  It is accessible with the
<code><a href="api.html#duk_push_thread_stash">duk_push_thread_stash()</a></code>
API call.</p><h2 class="sectiontitle" id="programming.10">Duktape version specific code <a class="sectionlink" href="#programming.10">§</a></h2><p>The Duktape version is available through the <code>DUK_VERSION</code> define,
with the numeric value <code>(major * 10000) + (minor * 100) + patch</code>.
The same value is available to Ecmascript code through <code>Duktape.version</code>.
Calling code can use this define for Duktape version specific code.</p><p>For C code:</p><pre class="c-code"><span class="preproc">#if</span><span class="normal"> </span><span class="symbol">(</span><span class="normal">DUK_VERSION </span><span class="symbol">&gt;=</span><span class="normal"> </span><span class="number">10203</span><span class="symbol">)</span>
<span class="comment">/* Duktape 1.2.3 or later */</span>
<span class="preproc">#elif</span><span class="normal"> </span><span class="symbol">(</span><span class="normal">DUK_VERSION </span><span class="symbol">&gt;=</span><span class="normal"> </span><span class="number">800</span><span class="symbol">)</span>
<span class="comment">/* Duktape 0.8.0 or later */</span>
<span class="preproc">#else</span>
<span class="comment">/* Duktape lower than 0.8.0 */</span>
<span class="preproc">#endif</span>
</pre><p>For Ecmascript code (also see <a href="#duktapebuiltins">Duktape built-ins</a>):</p><pre class="ecmascript-code"><span class="keyword">if</span><span class="normal"> </span><span class="symbol">(</span><span class="keyword">typeof</span><span class="normal"> Duktape </span><span class="symbol">!==</span><span class="normal"> </span><span class="string">'object'</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="function">print</span><span class="symbol">(</span><span class="string">'not Duktape'</span><span class="symbol">);</span>
<span class="cbracket">}</span><span class="normal"> </span><span class="keyword">else</span><span class="normal"> </span><span class="keyword">if</span><span class="normal"> </span><span class="symbol">(</span><span class="normal">Duktape</span><span class="symbol">.</span><span class="normal">version </span><span class="symbol">&gt;=</span><span class="normal"> </span><span class="number">10203</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="function">print</span><span class="symbol">(</span><span class="string">'Duktape 1.2.3 or higher'</span><span class="symbol">);</span>
<span class="cbracket">}</span><span class="normal"> </span><span class="keyword">else</span><span class="normal"> </span><span class="keyword">if</span><span class="normal"> </span><span class="symbol">(</span><span class="normal">Duktape</span><span class="symbol">.</span><span class="normal">version </span><span class="symbol">&gt;=</span><span class="normal"> </span><span class="number">800</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="function">print</span><span class="symbol">(</span><span class="string">'Duktape 0.8.0 or higher (but lower than 1.2.3)'</span><span class="symbol">);</span>
<span class="cbracket">}</span><span class="normal"> </span><span class="keyword">else</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="function">print</span><span class="symbol">(</span><span class="string">'Duktape lower than 0.8.0'</span><span class="symbol">);</span>
<span class="cbracket">}</span>
</pre><h2 class="sectiontitle" id="programming.11">Numeric error codes <a class="sectionlink" href="#programming.11">§</a></h2><p>When errors are created or thrown using the Duktape API, the caller
must assign a numeric error code to the error.  Error codes are
positive integers, with a range restricted to 24 bits at the
moment: the allowed error number range is thus [1,16777215].  Built-in
error codes are defined in <code>duktape.h</code>, e.g. <code>DUK_ERR_TYPE_ERROR</code>.</p><p>The remaining high bits are used internally to carry e.g. additional
flags.  Negative error values are used in the Duktape/C API as a
shorthand to automatically throw an error.</p><h2 class="sectiontitle" id="error-handling">Error handling <a class="sectionlink" href="#error-handling">§</a></h2><p>Error handling in the Duktape API is similar to how Ecmascript handles
errors: errors are thrown either explicitly or implicitly, then caught and
handled.  However, instead of a try-catch statement application code uses
<code><a href="api.html#taglist-protected">protected</a></code>
Duktape API calls to establish points in C code where errors can be caught
and handled.
An uncaught error causes the fatal error handler to be called, which is
considered an unrecoverable situation and should ordinarily be avoided,
see <a href="#normal-and-fatal-errors">Normal and fatal errors</a> and
<a href="http://wiki.duktape.org/HowtoFatalErrors.html">How to handle fatal errors</a>.</p><p>To avoid fatal errors, typical application code should establish an error
catch point before making other Duktape API calls.  This is done using
protected Duktape API calls, for example:</p><ul>
<li>Use protected calls to evaluate code
    (<a href="api.html#duk_peval">duk_peval()</a>), compile code
    (<a href="api.html#duk_pcompile">duk_pcompile()</a>), and call
    (<a href="api.html#duk_pcall">duk_pcall()</a>) functions.</li>
<li>Use a single <a href="api.html#duk_safe_call">duk_safe_call()</a> to
    establish an error catcher so that you can use unsafe primitives freely
    inside the safe call.</li>
</ul><p>An example of the first technique:</p><pre class="c-code"><span class="comment">/* Use duk_peval() variant to evaluate a file so that script errors are</span>
<span class="comment"> * handled safely.  Both syntax errors and runtime errors are caught.</span>
<span class="comment"> */</span>

<span class="function">push_file_as_string</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="string">"myscript.js"</span><span class="symbol">);</span>
<span class="keyword">if</span><span class="normal"> </span><span class="symbol">(</span><span class="function">duk_peval</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">!=</span><span class="normal"> </span><span class="number">0</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="comment">/* Use duk_safe_to_string() to convert error into string.  This API</span>
<span class="comment">     * call is guaranteed not to throw an error during the coercion.</span>
<span class="comment">     */</span>
<span class="normal">    </span><span class="function">printf</span><span class="symbol">(</span><span class="string">"Script error: %s</span><span class="specialchar">\n</span><span class="string">"</span><span class="symbol">,</span><span class="normal"> </span><span class="function">duk_safe_to_string</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">-</span><span class="number">1</span><span class="symbol">));</span>
<span class="cbracket">}</span>
<span class="function">duk_pop</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">);</span>
</pre><p>An example of the second technique:</p><pre class="c-code"><span class="comment">/* Use duk_safe_call() to wrap all unsafe code into a separate C function.</span>
<span class="comment"> * This approach has the advantage of covering all API calls automatically</span>
<span class="comment"> * but is a bit more verbose.</span>
<span class="comment"> */</span>

<span class="keyword">static</span><span class="normal"> </span><span class="usertype">duk_ret_t</span><span class="normal"> </span><span class="function">unsafe_code</span><span class="symbol">(</span><span class="usertype">duk_context</span><span class="normal"> </span><span class="symbol">*</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="type">void</span><span class="normal"> </span><span class="symbol">*</span><span class="normal">udata</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="comment">/* Here we can use unprotected calls freely. */</span>

<span class="normal">    </span><span class="symbol">(</span><span class="type">void</span><span class="symbol">)</span><span class="normal"> udata</span><span class="symbol">;</span><span class="normal">  </span><span class="comment">/* 'udata' may be used to pass e.g. a struct pointer */</span>

<span class="normal">    </span><span class="function">push_file_as_string</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="string">"myscript.js"</span><span class="symbol">);</span>
<span class="normal">    </span><span class="function">duk_eval</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">);</span>

<span class="normal">    </span><span class="comment">/* ... */</span>

<span class="normal">    </span><span class="keyword">return</span><span class="normal"> </span><span class="number">0</span><span class="symbol">;</span><span class="normal">  </span><span class="comment">/* success return, no return value */</span>
<span class="cbracket">}</span>

<span class="comment">/* elsewhere: */</span>

<span class="keyword">if</span><span class="normal"> </span><span class="symbol">(</span><span class="function">duk_safe_call</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> unsafe_code</span><span class="symbol">,</span><span class="normal"> NULL </span><span class="comment">/*udata*/</span><span class="symbol">,</span><span class="normal"> </span><span class="number">0</span><span class="normal"> </span><span class="comment">/*nargs*/</span><span class="symbol">,</span><span class="normal"> </span><span class="number">1</span><span class="normal"> </span><span class="comment">/*nrets */</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">!=</span><span class="normal"> </span><span class="number">0</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="comment">/* The 'nrets' argument should be at least 1 so that an error value</span>
<span class="comment">     * is left on the stack if an error occurs.  To avoid further errors,</span>
<span class="comment">     * use duk_safe_to_string() for safe error printing.</span>
<span class="comment">     */</span>
<span class="normal">    </span><span class="function">printf</span><span class="symbol">(</span><span class="string">"Unexpected error: %s</span><span class="specialchar">\n</span><span class="string">"</span><span class="symbol">,</span><span class="normal"> </span><span class="function">duk_safe_to_string</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">-</span><span class="number">1</span><span class="symbol">));</span>
<span class="cbracket">}</span>
<span class="function">duk_pop</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">);</span>
</pre><p>Even within protected calls there are some rare cases, such as internal
errors, that will either cause a fatal error or propagate an error outwards
from a protected API call.  These should only happen in abnormal conditions
and are not considered recoverable.  To handle also these cases well, a
production quality application should always have a fatal error handler with
a reasonable strategy for dealing with fatal errors.  Such a strategy is
necessarily context dependent, but could be something like:</p><ul>
<li>On an embedded device the fatal error handler could write the fatal
    error information to a flash file and reboot the device.  After the
    reboot, the fatal error could be reported to a diagnostics server so
    that it can be investigated.</li>
<li>On a UNIX system the fatal error handler could simply exit the process
    (the default fatal handler uses <code>abort()</code>) and let a wrapper
    script restart the application.</li>
</ul><p>Note that it may be fine for some applications to make API calls without
an error catcher and risk throwing uncaught errors leading to a fatal error.
It's not possible to continue execution after a fatal error, so such
applications would typically simply exit when a fatal error occurs.  Even
without an actual recovery strategy, a fatal error handler should be used to
e.g. write fatal error information to <code>stderr</code> before process exit.</p><a name="error-fatal-panic"></a><!-- for old links --><h2 class="sectiontitle" id="normal-and-fatal-errors">Normal and fatal errors <a class="sectionlink" href="#normal-and-fatal-errors">§</a></h2><p>An <b>ordinary error</b> is caused by a <code>throw</code> statement, a
<code><a href="api.html#duk_throw">duk_throw()</a></code>
API call (or similar), or by an internal, recoverable Duktape error.
Ordinary errors can be caught with a <code>try-catch</code> in Ecmascript
code or e.g. <code><a href="api.html#duk_pcall">duk_pcall()</a></code>
(see API calls tagged
<code><a href="api.html#taglist-protected">protected</a></code>)
in C code.</p><p>A <b>fatal error</b> is caused by an uncaught error, an explicit call to
<code><a href="api.html#duk_fatal">duk_fatal()</a></code>, or an
unrecoverable error inside Duktape.  Each Duktape heap has a heap-wide fatal
error handler registered in
<code><a href="api.html#duk_create_heap">duk_create_heap()</a></code>; if no
handler is given a built-in default handler is used.  There's no safe way to
resume execution after a fatal error, so that a fatal error handler must not
return or call into the Duktape API.  Instead the handler should e.g. write
out the message to the console or a log file and then exit the process (or
restart an embedded device).</p><p>Fatal errors may also happen without any heap context, so that Duktape
can't look up a possible heap-specific fatal error handler.  Duktape will then
always call the built-in default fatal error handler (with the handler
userdata argument set to NULL).  Fatal errors handled this way are currently
limited to assertion failures, so that if you don't enable assertions, no such
errors will currently occur.  All fatal error handling goes through the
heap-associated fatal error handler which is in direct application control.</p><div class="note">
The built-in default fatal error handler will write a debug log message
(but <b>won't</b> write anything to <code>stdout</code> to <code>stderr</code>),
and will then call <code>abort()</code>; if that fails, it enters an
infinite loop to ensure execution doesn't resume after a fatal error.  It is
<b>strongly recommended</b> to both (1) provide a custom fatal error handler
in heap creation and (2) replace the built-in default fatal error handler using
the <code>DUK_USE_FATAL_HANDLER()</code> option in <code>duk_config.h</code>.
</div><p>See <a href="http://wiki.duktape.org/HowtoFatalErrors.html">How to handle fatal errors</a>
for more detail and examples.</p><hr/><h1 class="sectiontitle" id="stacktypes">Stack types <a class="sectionlink" href="#stacktypes">§</a></h1><h2 class="sectiontitle" id="type-table">Overview <a class="sectionlink" href="#type-table">§</a></h2><div class="table-wrap">
<table>
<tr class="header"><th>Type</th><th>Type constant</th><th>Type mask constant</th><th>Description</th></tr>
<tr><td><a href="#type-none">(none)</a></td><td>DUK_TYPE_NONE</td><td>DUK_TYPE_MASK_NONE</td><td>no type (missing value, invalid index, etc)</td></tr>
<tr><td><a href="#type-undefined">undefined</a></td><td>DUK_TYPE_UNDEFINED</td><td>DUK_TYPE_MASK_UNDEFINED</td><td><code>undefined</code></td></tr>
<tr><td><a href="#type-null">null</a></td><td>DUK_TYPE_NULL</td><td>DUK_TYPE_MASK_NULL</td><td><code>null</code></td></tr>
<tr><td><a href="#type-boolean">boolean</a></td><td>DUK_TYPE_BOOLEAN</td><td>DUK_TYPE_MASK_BOOLEAN</td><td><code>true</code> and <code>false</code></td></tr>
<tr><td><a href="#type-number">number</a></td><td>DUK_TYPE_NUMBER</td><td>DUK_TYPE_MASK_NUMBER</td><td>IEEE double</td></tr>
<tr><td><a href="#type-string">string</a></td><td>DUK_TYPE_STRING</td><td>DUK_TYPE_MASK_STRING</td><td>immutable (plain) string or (plain) Symbol</td></tr>
<tr><td><a href="#type-object">object</a></td><td>DUK_TYPE_OBJECT</td><td>DUK_TYPE_MASK_OBJECT</td><td>object with properties</td></tr>
<tr><td><a href="#type-buffer">buffer</a></td><td>DUK_TYPE_BUFFER</td><td>DUK_TYPE_MASK_BUFFER</td><td>mutable (plain) byte buffer, fixed/dynamic/external; mimics an Uint8Array</td></tr>
<tr><td><a href="#type-pointer">pointer</a></td><td>DUK_TYPE_POINTER</td><td>DUK_TYPE_MASK_POINTER</td><td>opaque pointer (void *)</td></tr>
<tr><td><a href="#type-lightfunc">lightfunc</a></td><td>DUK_TYPE_LIGHTFUNC</td><td>DUK_TYPE_MASK_LIGHTFUNC</td><td>plain Duktape/C function pointer (non-object); mimics a Function</td></tr>
</table>
</div><h2 class="sectiontitle" id="type-memory-allocations">Memory allocations <a class="sectionlink" href="#type-memory-allocations">§</a></h2><p>The following stack types involve additional heap allocations:</p><ul>
<li>String: a single allocation contains a combined heap and string header,
    followed by the immutable string data.</li>
<li>Object: one allocation is used for a combined heap and object header,
    and another allocation is used for object properties.  The property
    allocation contains both array entries and normal properties, and if
    the object is large enough, a hash table to speed up lookups.</li>
<li>Buffer: for fixed buffers a single allocation contains a combined heap
    and buffer header, followed by the mutable fixed-size buffer.  For
    dynamic buffers the current buffer is allocated separately.  For
    external buffers a single heap object is allocated and points to
    a user buffer.</li>
</ul><p>Note that while strings and buffers are considered a primitive (pass-by-value)
types, they are a heap allocated type from a memory allocation viewpoint.</p><h2 class="sectiontitle" id="type-pointer-stability">Pointer stability <a class="sectionlink" href="#type-pointer-stability">§</a></h2><p>Heap objects allocated by Duktape have stable pointers: the objects are
not relocated in memory while they are reachable from a garbage collection
point of view.  This is the case for the main heap object, but not
necessarily for any additional allocations related to the object, such as
dynamic property tables or dynamic buffer data area.  A heap object is
reachable e.g. when it resides on the value stack of a reachable thread or
is reachable through the global object.  Once a heap object becomes
unreachable any pointers held by user C code referring to the object are
unsafe and should no longer be dereferenced.</p><p>In practice the only heap allocated data directly referenced by user code
are strings, fixed buffers, and dynamic buffers.  The data area of strings
and fixed buffers is stable; it is safe to keep a C pointer referring to the
data even after a Duktape/C function returns as long the string or fixed
buffer remains reachable from a garbage collection point of view at all times.
Note that this is <i>not</i> the case for Duktape/C value stack arguments, for
instance, unless specific arrangements are made.</p><p>The data area of a dynamic buffer does <b>not</b> have a stable pointer.
The buffer itself has a heap header with a stable address but the current
buffer is allocated separately and potentially relocated when the buffer
is resized.  It is thus unsafe to hold a pointer to a dynamic buffer's data
area across a buffer resize, and it's probably best not to hold a pointer
after a Duktape/C function returns (as there would be no easy way of being
sure that the buffer hadn't been resized).  The data area of an external
buffer also has a potentially changing pointer, but the pointer is only
changed by an explicit user API call.</p><p>For external buffers the stability of the data pointer is up to the user
code which sets and updates the pointer.</p><h2 class="sectiontitle" id="type-masks">Type masks <a class="sectionlink" href="#type-masks">§</a></h2><p>Type masks allows calling code to easily check whether a type belongs to
a certain type set.  For instance, to check that a certain stack value is
a number, string, or an object:</p><pre class="c-code"><span class="keyword">if</span><span class="normal"> </span><span class="symbol">(</span><span class="function">duk_get_type_mask</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">-</span><span class="number">3</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">&amp;</span><span class="normal"> </span><span class="symbol">(</span><span class="normal">DUK_TYPE_MASK_NUMBER </span><span class="symbol">|</span>
<span class="normal">                                  DUK_TYPE_MASK_STRING </span><span class="symbol">|</span>
<span class="normal">                                  DUK_TYPE_MASK_OBJECT</span><span class="symbol">))</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="function">printf</span><span class="symbol">(</span><span class="string">"type is number, string, or object</span><span class="specialchar">\n</span><span class="string">"</span><span class="symbol">);</span>
<span class="cbracket">}</span>
</pre><p>There is a specific API call for matching a set of types even more
conveniently:</p><pre class="c-code"><span class="keyword">if</span><span class="normal"> </span><span class="symbol">(</span><span class="function">duk_check_type_mask</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">-</span><span class="number">3</span><span class="symbol">,</span><span class="normal"> DUK_TYPE_MASK_NUMBER </span><span class="symbol">|</span>
<span class="normal">                                 DUK_TYPE_MASK_STRING </span><span class="symbol">|</span>
<span class="normal">                                 DUK_TYPE_MASK_OBJECT</span><span class="symbol">))</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="function">printf</span><span class="symbol">(</span><span class="string">"type is number, string, or object</span><span class="specialchar">\n</span><span class="string">"</span><span class="symbol">);</span>
<span class="cbracket">}</span>
</pre><p>These are faster and more compact than the alternatives:</p><pre class="c-code"><span class="comment">// alt 1</span>
<span class="keyword">if</span><span class="normal"> </span><span class="symbol">(</span><span class="function">duk_is_number</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">-</span><span class="number">3</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">||</span><span class="normal"> </span><span class="function">duk_is_string</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">-</span><span class="number">3</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">||</span><span class="normal"> </span><span class="function">duk_is_object</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">-</span><span class="number">3</span><span class="symbol">))</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="function">printf</span><span class="symbol">(</span><span class="string">"type is number, string, or object</span><span class="specialchar">\n</span><span class="string">"</span><span class="symbol">);</span>
<span class="cbracket">}</span>

<span class="comment">// alt 2</span>
<span class="type">int</span><span class="normal"> t </span><span class="symbol">=</span><span class="normal"> </span><span class="function">duk_get_type</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">-</span><span class="number">3</span><span class="symbol">);</span>
<span class="keyword">if</span><span class="normal"> </span><span class="symbol">(</span><span class="normal">t </span><span class="symbol">==</span><span class="normal"> DUK_TYPE_NUMBER </span><span class="symbol">||</span><span class="normal"> t </span><span class="symbol">==</span><span class="normal"> DUK_TYPE_STRING </span><span class="symbol">||</span><span class="normal"> t </span><span class="symbol">==</span><span class="normal"> DUK_TYPE_OBJECT</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="function">printf</span><span class="symbol">(</span><span class="string">"type is number, string, or object</span><span class="specialchar">\n</span><span class="string">"</span><span class="symbol">);</span>
<span class="cbracket">}</span>
</pre><h2 class="sectiontitle" id="type-none">None <a class="sectionlink" href="#type-none">§</a></h2><p>The <b>none</b> type is not actually a type but is used in the API to
indicate that a value does not exist, a stack index is invalid, etc.</p><h2 class="sectiontitle" id="type-undefined">Undefined <a class="sectionlink" href="#type-undefined">§</a></h2><p>The <b>undefined</b> type maps to Ecmascript <code>undefined</code>, which is
distinguished from a <code>null</code>.</p><p>Values read from outside the active value stack range read back as
<b>undefined</b>.</p><h2 class="sectiontitle" id="type-null">Null <a class="sectionlink" href="#type-null">§</a></h2><p>The <b>null</b> type maps to Ecmascript <code>null</code>.</p><h2 class="sectiontitle" id="type-boolean">Boolean <a class="sectionlink" href="#type-boolean">§</a></h2><p>The <b>boolean</b> type is represented in the C API as an integer: zero for false,
and non-zero for true.</p><p>Whenever giving boolean values as arguments in API calls, any non-zero value is
accepted as a "true" value.  Whenever API calls return boolean values, the value
<code>1</code> is always used for a "true" value.  This allows certain C idioms to be
used.  For instance, a bitmask can be built directly based on API call return values,
as follows:
</p><pre class="c-code"><span class="comment">/* this works and generates nice code */</span>
<span class="type">int</span><span class="normal"> bitmask </span><span class="symbol">=</span><span class="normal"> </span><span class="symbol">(</span><span class="function">duk_get_boolean</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">-</span><span class="number">3</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">&lt;&lt;</span><span class="normal"> </span><span class="number">2</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">|</span>
<span class="normal">              </span><span class="symbol">(</span><span class="function">duk_get_boolean</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">-</span><span class="number">2</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">&lt;&lt;</span><span class="normal"> </span><span class="number">1</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">|</span>
<span class="normal">              </span><span class="function">duk_get_boolean</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">-</span><span class="number">1</span><span class="symbol">);</span>

<span class="comment">/* more verbose variant not relying on "true" being represented by 1 */</span>
<span class="type">int</span><span class="normal"> bitmask </span><span class="symbol">=</span><span class="normal"> </span><span class="symbol">((</span><span class="function">duk_get_boolean</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">-</span><span class="number">3</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">?</span><span class="normal"> </span><span class="number">1</span><span class="normal"> </span><span class="symbol">:</span><span class="normal"> </span><span class="number">0</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">&lt;&lt;</span><span class="normal"> </span><span class="number">2</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">|</span>
<span class="normal">              </span><span class="symbol">((</span><span class="function">duk_get_boolean</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">-</span><span class="number">2</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">?</span><span class="normal"> </span><span class="number">1</span><span class="normal"> </span><span class="symbol">:</span><span class="normal"> </span><span class="number">0</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">&lt;&lt;</span><span class="normal"> </span><span class="number">1</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">|</span>
<span class="normal">              </span><span class="symbol">(</span><span class="function">duk_get_boolean</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">-</span><span class="number">1</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">?</span><span class="normal"> </span><span class="number">1</span><span class="normal"> </span><span class="symbol">:</span><span class="normal"> </span><span class="number">0</span><span class="symbol">);</span>

<span class="comment">/* another verbose variant */</span>
<span class="type">int</span><span class="normal"> bitmask </span><span class="symbol">=</span><span class="normal"> </span><span class="symbol">(</span><span class="function">duk_get_boolean</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">-</span><span class="number">3</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">?</span><span class="normal"> </span><span class="symbol">(</span><span class="number">1</span><span class="normal"> </span><span class="symbol">&lt;&lt;</span><span class="normal"> </span><span class="number">2</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">:</span><span class="normal"> </span><span class="number">0</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">|</span>
<span class="normal">              </span><span class="symbol">(</span><span class="function">duk_get_boolean</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">-</span><span class="number">2</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">?</span><span class="normal"> </span><span class="symbol">(</span><span class="number">1</span><span class="normal"> </span><span class="symbol">&lt;&lt;</span><span class="normal"> </span><span class="number">1</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">:</span><span class="normal"> </span><span class="number">0</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">|</span>
<span class="normal">              </span><span class="symbol">(</span><span class="function">duk_get_boolean</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">-</span><span class="number">1</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">?</span><span class="normal"> </span><span class="number">1</span><span class="normal"> </span><span class="symbol">:</span><span class="normal"> </span><span class="number">0</span><span class="symbol">);</span>
</pre><h2 class="sectiontitle" id="type-number">Number <a class="sectionlink" href="#type-number">§</a></h2><p>The <b>number</b> type is an IEEE double, including +/- Infinity and NaN values.
Zero sign is also preserved.  An IEEE double represents all integers up to 53 bits
accurately.</p><p>IEEE double allows NaN values to have additional signaling bits.  Because these
bits are used by Duktape internal tagged type representation (when using 8-byte
packed values), NaN values in the Duktape API are normalized.  Concretely, if you
push a certain NaN value to the value stack, another (normalized) NaN value may
come out.  Don't rely on NaNs preserving their exact form.</p><h2 class="sectiontitle" id="type-string">String <a class="sectionlink" href="#type-string">§</a></h2><p>The <b>string</b> stack type is used to represent both plain strings and
plain Symbols (introduced in ES2015).  A string is an arbitrary byte sequence
of a certain length which may contain internal NUL (0x00) values.  Strings are
always automatically NUL terminated for C coding convenience.  The NUL terminator
is not counted as part of the string length.  For instance, the string
<code>"foo"</code> has byte length 3 and is stored in memory as
<code>{ 'f', 'o', 'o', '\0' }</code>.  Because of the guaranteed NUL termination,
strings can always be pointed to using a simple <code>const char *</code> as long
as internal NULs are not an issue for the application; if they are, the explicit
byte length of the string can be queried with the API.  Calling code can refer
directly to the string data held by Duktape.  Such string data pointers are valid
(and stable) for as long as a string is reachable in the Duktape heap.</p><p>Strings are <a href="http://en.wikipedia.org/wiki/String_interning">interned</a>
for efficiency: only a single copy of a certain string ever exists at a time.
Strings are immutable and must NEVER be changed by calling C code.  Doing so will
lead to very mysterious issues which are hard to diagnose.</p><p>Calling code most often deals with Ecmascript strings, which may contain
arbitrary 16-bit codepoints in the range U+0000 to U+FFFF but cannot represent
non-<a href="http://en.wikipedia.org/wiki/Basic_Multilingual_Plane#Basic_Multilingual_Plane">BMP</a>
codepoints.  This is how strings are defined in the Ecmascript standard.
In Duktape, Ecmascript strings are encoded with
<a href="http://en.wikipedia.org/wiki/CESU-8">CESU-8</a> encoding.  CESU-8
matches <a href="http://en.wikipedia.org/wiki/UTF-8">UTF-8</a> except that it
allows codepoints in the surrogate pair range (U+D800 to U+DFFF) to be encoded
directly (prohibited in UTF-8).  CESU-8, like UTF-8, encodes all 7-bit ASCII
characters as-is which is convenient for C code.  For example:</p><ul>
<li>U+0041 ("A") encodes to <code>41</code>.</li>
<li>U+1234 (ETHIOPIC SYLLABLE SEE) encodes to <code>e1 88 b4</code>.</li>
<li>U+D812 (high surrogate) encodes to <code>ed a0 92</code>. This would be
    <a href="http://en.wikipedia.org/wiki/UTF-8#Invalid_code_points">invalid UTF-8</a>.</li>
</ul><a name="extended-utf8"></a><p>Duktape also uses extended strings internally.  Codepoints up to U+10FFFF
can be represented with UTF-8, and codepoints above that up to full 32 bits
can be represented with
<a href="http://en.wikipedia.org/wiki/UTF-8#Extending_from_31_bit_to_36_bit_range">extended UTF-8</a>.
The extended UTF-8 encoding used by Duktape is described in the table below.
The leading byte is shown in binary (with "x" marking data bits) while
continuation bytes are marked with "C" (indicating the bit sequence 10xxxxxx):</p><table>
<thead>
<tr class="header"><th>Codepoint range</th><th>Bits</th><th>Byte sequence</th><th>Notes</th></tr>
</thead>
<tbody>
<tr><td>U+0000 to U+007F</td><td>7</td><td>0xxxxxxx</td><td></td></tr>
<tr><td>U+0080 to U+07FF</td><td>11</td><td>110xxxxx C</td><td></td></tr>
<tr><td>U+0800 to U+FFFF</td><td>16</td><td>1110xxxx C C</td><td>U+D800 to U+DFFF allowed (unlike UTF-8)</td></tr>
<tr><td>U+1 0000 to U+1F FFFF</td><td>21</td><td>11110xxx C C C</td><td>Above U+10FFFF allowed (unlike UTF-8)</td></tr>
<tr><td>U+20 0000 to U+3FF FFFF</td><td>26</td><td>111110xx C C C C</td><td></td></tr>
<tr><td>U+400 0000 to U+7FFF FFFF</td><td>31</td><td>1111110x C C C C C</td><td></td></tr>
<tr><td>U+8000 0000 to U+F FFFF FFFF</td><td>36</td><td>11111110 C C C C C C</td><td>Only 32 bits used in practice (up to U+FFFF FFFF)</td></tr>
</tbody>
</table><p>The downside of the encoding for codepoints above U+7FFFFFFF is that
the leading byte will be <code>0xFE</code> which conflicts with Unicode byte order
marker encoding.  This is not a practical concern in Duktape's internal use.</p><p>Finally, invalid extended UTF-8 byte sequences are used for special purposes
such as representing Symbol values.  Invalid extened UTF-8/CESU-8 byte sequences
never conflict with standard Ecmascript strings (which are CESU-8) and will remain
cleanly separated within object property tables.  For more information see
<a href="#symbols">Symbols</a> and
<a href="https://github.com/svaarala/duktape/blob/master/doc/symbols.rst">symbols.rst</a>.</p><p>Strings with invalid extended UTF-8 sequences can be pushed on the value stack
from C code and also passed to Ecmascript functions, with two caveats:</p><ul>
<li>If the invalid byte sequence matches the internal format used to represent
    Symbols, the value will appear as a Symbol rather than a string for Ecmascript
    code.  For example, <code>typeof val</code> will be <code>symbol</code>.</li>
<li>Behavior of string operations on invalid byte sequences if not well defined
    and results may vary, and change even in minor Duktape version updates.</li>
</ul><h2 class="sectiontitle" id="type-object">Object <a class="sectionlink" href="#type-object">§</a></h2><p>The <b>object</b> type includes Ecmascript objects and arrays, functions,
threads (coroutines), and buffer objects.  In other words, anything with
properties is an object.  Properties are key-value pairs with a string key
and an arbitrary value (including <b>undefined</b>).</p><p>Objects may participate in garbage collection finalization.</p><h2 class="sectiontitle" id="type-buffer">Buffer <a class="sectionlink" href="#type-buffer">§</a></h2><p>The plain <b>buffer</b> type is a raw buffer for user data.  It's much
more memory efficient than standard buffer object types like Uint8Array
or Node.js Buffer.  There are three plain buffer sub-types:</p><table>
<tr>
<th>Buffer sub-type</th>
<th>Data pointer</th>
<th>Resizable</th>
<th>Memory managed by</th>
<th>Description</th>
</tr>
<tr>
<td>Fixed</td>
<td>Stable, non-NULL</td>
<td>No</td>
<td>Duktape</td>
<td>Buffer size is fixed at creation, memory is managed automatically by
    Duktape.  Fixed buffers have an unchanging (stable) non-NULL data
    pointer.</td>
</tr>
<tr>
<td>Dynamic</td>
<td>Unstable, may be NULL</td>
<td>Yes</td>
<td>Duktape</td>
<td>Buffer size can be changed after creation, memory is managed
    automatically by Duktape.  Requires two memory allocations internally
    to allow resizing.  Data pointer may change if buffer is resized.
    Zero-size buffer may have a NULL data pointer.</td>
</tr>
<tr>
<td>External</td>
<td>Unstable, may be NULL</td>
<td>Yes</td>
<td>Duktape and user code</td>
<td>Buffer data is externally allocated.  Duktape allocates and manages
    a heap allocated buffer header structure, while the data area pointer
    and length are configured by user code explicitly.  External buffers
    are useful to allow a buffer to point to data structures outside
    Duktape heap, e.g. a frame buffer allocated by a graphics library.
    Zero-size buffer may have a NULL data pointer.</td>
</tr>
</table><p>Unlike strings, buffer data areas are not automatically NUL-terminated
and calling code must never access bytes beyond the currently allocated
buffer size.  The data pointer of a zero-size dynamic or external buffer
may be NULL; fixed buffers always have a non-NULL data pointer.</p><p>Fixed and dynamic buffers are automatically garbage collected.  This
also means that C code must not hold onto a buffer data pointer unless the
buffer is reachable to Duktape, e.g. resides in an active value stack.
The data area of an external buffer is not automatically garbage collected
so user code is responsible for managing its life cycle.  User code must also
make sure that no external buffer value is accessed when the external buffer
is no longer (or not yet) valid.</p><p>Plain buffers mimic Uint8Array objects to a large extent, so they are
a non-standard, memory efficient alternative to working with e.g. ArrayBuffer
and typed arrays.  The standard buffer objects are implemented on top of plain
buffers, so that e.g. an ArrayBuffer will be backed by a plain buffer.  See
<a href="#bufferobjects">Buffer objects</a> for more discussion.</p><p>A few notes:</p><ul>
<li>Because the value written to a buffer index is number coerced, assigning
a one-character value does not work as often expected.  For instance, 
<code>buf[123] = 'x'</code> causes zero to be written to the buffer, as
ToNumber('x') = 0.  For clarity, you should only assign number values,
e.g. <code>buf[123] = 0x78</code>.</li>
<li>There is a fast path for reading and writing numeric indices of plain buffer
values, e.g. <code>x = buf[123]</code> or <code>buf[123] = x</code>.  A similar
fast path exists for the different buffer object values.</li>
<li>Buffer virtual properties are not currently implemented in
<code>defineProperty()</code>, so you can't write to buffer indices or
buffer <code>length</code> with <code>defineProperty()</code> now (attempt
to do so results in a <code>TypeError</code>).</li>
</ul><h2 class="sectiontitle" id="type-pointer">Pointer <a class="sectionlink" href="#type-pointer">§</a></h2><p>The <b>pointer</b> type is a raw, uninterpreted C pointer, essentially
a <code>void *</code>.  Pointers can be used to point to native objects (memory
allocations, handles, etc), but because Duktape doesn't know their use, they
are not automatically garbage collected.  You can, however, put one or more
pointers inside an object and use the object finalizer to free the
native resources related to the pointer(s).</p><h2 class="sectiontitle" id="type-lightfunc">Lightfunc <a class="sectionlink" href="#type-lightfunc">§</a></h2><p>The <b>lightfunc</b> type is a plain Duktape/C function pointer and a small
set of control flags packed into a single tagged value which requires no separate
heap allocations.  The control flags (16 bits currently) encode:
(1) number of stack arguments expected by the Duktape/C function (0 to 14 or
varargs), (2) virtual <code>length</code> property value (0 to 15), and
(3) a magic value (-128 to 127).</p><p>Lightfuncs are a separate tagged type in the Duktape C API, but behave mostly
like Function objects for Ecmascript code.  They have significant limitations
compared to ordinary Function objects, the most important being:</p><ul>
<li>Lightfuncs cannot hold own properties.  They have a fixed virtual <code>.name</code>
    property which appears in tracebacks, and a virtual <code>.length</code> property.
    Other properties are inherited from <code>Function.prototype</code>.</li>
<li>Lightfuncs can be used as constructor functions, but cannot have a
    <code>.prototype</code> property.  If you need to construct objects which
    don't inherit from <code>Object.prototype</code> (the default), you need to
    either (a) construct and return an instance explicitly in the constructor or
    (b) explicitly override the internal prototype of the default instance in the
    constructor.</li>
<li>Lightfuncs can be used as accessor properties (getters/setters), but they
    get converted to actual functions so that their memory advantage is lost.
    See
    <a href="https://github.com/svaarala/duktape/blob/master/tests/ecmascript/test-dev-lightfunc-accessor.js">test-dev-lightfunc-accessor.js</a>.</li>
<li>Lightfuncs cannot have a finalizer as they are a primitive type and
    don't have a reference count field or otherwise participate in garbage
    collection.  See
    <a href="https://github.com/svaarala/duktape/blob/master/tests/ecmascript/test-dev-lightfunc-finalizer.js">test-dev-lightfunc-finalizer.js</a>.</li>
</ul><p>Lightfuncs are useful for very low memory environments where the memory
impact of ordinary Function objects matters.  See
<a href="#functionobjects">Function objects</a> for more discussion.</p><hr/><h1 class="sectiontitle" id="ctypes">API C types <a class="sectionlink" href="#ctypes">§</a></h1><p>Duktape API uses typedef-wrapped C types such as <code>duk_int_t</code>,
<code>duk_idx_t</code>, and <code>duk_ret_t</code> almost exclusively to ensure
portability to exotic platforms.  On most platforms these map directly to signed
or unsigned <code>int</code>; the wrappers make it possible to support platforms
where usual type assumptions (like having a 32-bit <code>int</code>) don't hold.
See Wiki article <a href="http://wiki.duktape.org/ApiCTypes.html">API C types</a>
for a detailed discussion.</p><p>Summary of best practices:</p><ul>
<li>Use Duktape API types such as <code>duk_idx_t</code> and <code>duk_ret_t</code>
    when declaring variables for maximum portability.  Alternatively you may
    use plain types (like <code>long</code>) but your code will be less portable
    and you may need to use casts to avoid warnings.</li>
<li>In <code>printf()</code> and <code>duk_push_sprintf()</code> formatting
    cast Duktape types to a wide integer type and use a standard format specifier.
    Example: <code>printf("Result: %ld\n", (long) duk_get_int(ctx, -3));</code>.</li>
<li>Use the <code>L</code> (or <code>UL</code>) suffix for constants which
    are larger than 16 bits to maximize portability.  Like the <code>int</code>
    type, integer constants without a suffix are only guaranteed to be 16 bits
    wide.  With the <code>L</code> suffix constants are guaranteed to be at least
    32 bits wide.  Example: <code>duk_push_int(ctx, 1234567L);</code>.</li>
</ul><hr/><h1 class="sectiontitle" id="typealgorithms">Type algorithms <a class="sectionlink" href="#typealgorithms">§</a></h1><p>This section describes how type-related Ecmascript algorithms
like comparisons and coercions are extended to Duktape custom types.
Duktape specific type algorithms (<code>ToBuffer()</code> and <code>ToPointer()</code>)
are also discussed.</p><h2 class="sectiontitle" id="typealgorithms.1">Notation <a class="sectionlink" href="#typealgorithms.1">§</a></h2><p>The following shorthand is used to indicate how values are compared:</p><table class="typeshorthand">
<thead>
<tr><th>Value</th><th>Description</th></tr>
</thead>
<tbody>
<tr><td>t</td><td>compares to true</td></tr>
<tr><td>f</td><td>compares to false</td></tr>
<tr><td>s</td><td>simple compare: boolean-to-boolean, string-to-string (string contents compared)</td></tr>
<tr><td>n</td><td>number compare: NaN values compare false, zeroes compare true regardless of sign (e.g. +0 == -0)</td></tr>
<tr><td>N</td><td>number compare in SameValue: NaN values compare true, zeroes compare with sign (e.g. SameValue(+0,-0) is false)</td></tr>
<tr><td>p</td><td>heap pointer compare</td></tr>
<tr><td>L</td><td>lightfunc compare: to be considered equal, Duktape/C function pointers and
                  internal control flags (including the "magic" value) must match</td></tr>
<tr><td>1</td><td>string vs. number: coerce string with ToNumber() and retry comparison</td></tr>
<tr><td>2</td><td>boolean vs. any: coerce boolean with ToNumber() and retry comparison</td></tr>
<tr><td>3</td><td>object vs. string/number: coerce object with ToPrimitive() and retry comparison</td></tr>
</tbody>
</table><p>Note that Boolean objects, String objects, and Number objects compare as any
other objects instead of being automatically unboxed.  For example, non-strict
equality compares plain string values with a byte-by-byte comparison, but String
objects are compared by object reference (like any other objects).</p><h2 class="sectiontitle" id="non-strict-equality-algorithm">Equality (non-strict) <a class="sectionlink" href="#non-strict-equality-algorithm">§</a></h2><p>Non-strict equality comparison is specified in
<a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3">The Abstract Equality Comparison Algorithm</a>
for standard types.  Custom type behavior is as follows:</p><ul>
<li>Buffer: plain buffers are compared by their heap pointer (reference), no
    content comparison is done.  This matches Uint8Array behavior.</li>
<li>Pointer: comparison against any other type returns false.  Comparison to a
    pointer returns true if and only if the pointer values are the same.  Note
    in particular that comparing a number to a pointer returns false.  This seems
    a bit unintuitive, but numbers cannot represent 64-pointers accurately,
    comparing numbers and pointers might be error prone.</li>
<li>Lightfunc: comparison against any other type returns false.  Comparison
    to a lightfunc returns true if and only if both the Duktape/C function
    pointers and internal control flags (including the "magic" value) match.
    Note that a lightfunc never compares equal to an ordinary Function object,
    even when the Function object was created by coercing a lightfunc to an object.</li>
</ul><p>The standard behavior as well as behavior for Duktape custom types is summarized in the table below:</p><table class="typecomparison">
<thead>
<tr><th> </th><th>und</th><th>nul</th><th>boo</th><th>num</th><th>str</th><th>obj</th><th>buf</th><th>ptr</th><th>lfn</th></tr>
</thead>
<tbody>
<tr><th>und</th><td>t  </td><td>t  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td></tr>
<tr><th>nul</th><td> </td><td>t  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td></tr>
<tr><th>boo</th><td> </td><td> </td><td>s  </td><td>2  </td><td>2  </td><td>2  </td><td>f  </td><td>f  </td><td>f  </td></tr>
<tr><th>num</th><td> </td><td> </td><td> </td><td>n  </td><td>1  </td><td>3  </td><td>f  </td><td>f  </td><td>f  </td></tr>
<tr><th>str</th><td> </td><td> </td><td> </td><td> </td><td>s  </td><td>3  </td><td>f  </td><td>f  </td><td>f  </td></tr>
<tr><th>obj</th><td> </td><td> </td><td> </td><td> </td><td> </td><td>p  </td><td>f  </td><td>f  </td><td>f  </td></tr>
<tr><th>buf</th><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td>p  </td><td>f  </td><td>f  </td></tr>
<tr><th>ptr</th><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td>s  </td><td>f  </td></tr>
<tr><th>lfn</th><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td>L  </td></tr>
</tbody>
</table><h2 class="sectiontitle" id="strict-equality-algorithm">Strict equality <a class="sectionlink" href="#strict-equality-algorithm">§</a></h2><p>Strict equality is much more straightforward and preferable whenever
possible for simplicity and performance.  It is described in
<a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.6">The Strict Equality Comparison Algorithm</a>
for standard types.  Custom type behavior is as follows:</p><ul>
<li>Buffer: like non-strict equality.</li>
<li>Pointer: like non-strict equality.</li>
<li>Lightfunc: like non-strict equality.</li>
</ul><p>The standard behavior as well as behavior for Duktape custom types is summarized in the table below:</p><table class="typecomparison">
<thead>
<tr><th> </th><th>und</th><th>nul</th><th>boo</th><th>num</th><th>str</th><th>obj</th><th>buf</th><th>ptr</th><th>lfn</th></tr>
</thead>
<tbody>
<tr><th>und</th><td>t  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td></tr>
<tr><th>nul</th><td> </td><td>t  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td></tr>
<tr><th>boo</th><td> </td><td> </td><td>s  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td></tr>
<tr><th>num</th><td> </td><td> </td><td> </td><td>n  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td></tr>
<tr><th>str</th><td> </td><td> </td><td> </td><td> </td><td>s  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td></tr>
<tr><th>obj</th><td> </td><td> </td><td> </td><td> </td><td> </td><td>p  </td><td>f  </td><td>f  </td><td>f  </td></tr>
<tr><th>buf</th><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td>p  </td><td>f  </td><td>f  </td></tr>
<tr><th>ptr</th><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td>s  </td><td>f  </td></tr>
<tr><th>lfn</th><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td>L  </td></tr>
</tbody>
</table><h2 class="sectiontitle" id="samevalue-algorithm">SameValue <a class="sectionlink" href="#samevalue-algorithm">§</a></h2><p>The <code>SameValue</code> algorithm is not easy to invoke from user code.
It is used by e.g. <code>Object.defineProperty()</code> when checking whether
a property value is about to change.  SameValue is even stricter than a
strict equality comparison, and most notably differs in how numbers are compared.
It is specified in
<a href="http://www.ecma-international.org/ecma-262/5.1/#sec-9.12">The SameValue algorithm</a>
for standard types.  Custom type behavior is as follows:</p><ul>
<li>Buffer: like non-strict (and strict) equality.</li>
<li>Pointer: like non-strict (and strict) equality.</li>
<li>Lightfunc: like non-strict (and strict equality).</li>
</ul><p>The standard behavior as well as behavior for Duktape custom types is summarized in the table below:</p><table class="typecomparison">
<thead>
<tr><th> </th><th>und</th><th>nul</th><th>boo</th><th>num</th><th>str</th><th>obj</th><th>buf</th><th>ptr</th><th>lfn</th></tr>
</thead>
<tbody>
<tr><th>und</th><td>t  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td></tr>
<tr><th>nul</th><td> </td><td>t  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td></tr>
<tr><th>boo</th><td> </td><td> </td><td>s  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td></tr>
<tr><th>num</th><td> </td><td> </td><td> </td><td>N  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td></tr>
<tr><th>str</th><td> </td><td> </td><td> </td><td> </td><td>s  </td><td>f  </td><td>f  </td><td>f  </td><td>f  </td></tr>
<tr><th>obj</th><td> </td><td> </td><td> </td><td> </td><td> </td><td>p  </td><td>f  </td><td>f  </td><td>f  </td></tr>
<tr><th>buf</th><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td>p  </td><td>f  </td><td>f  </td></tr>
<tr><th>ptr</th><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td>s  </td><td>f  </td></tr>
<tr><th>lfn</th><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td>L  </td></tr>
</tbody>
</table><h2 class="sectiontitle" id="type-conversion-and-testing">Type conversion and testing <a class="sectionlink" href="#type-conversion-and-testing">§</a></h2><p>The custom types behave as follows for Ecmascript coercions described
<a href="http://www.ecma-international.org/ecma-262/5.1/#sec-9">Type Conversion and Testing</a>
(except SameValue which was already covered above):</p><table>
<thead>
<tr><th> </th><th>buffer</th><th>pointer</th><th>lightfunc</th></tr>
</thead>
<tbody>
<tr><th>DefaultValue</th><td>Usually <code>"[object Uint8Array]"</code>; like Uint8Array</td><td>TypeError</td><td><code>"light_&lt;PTR&gt;_&lt;FLAGS&gt;"</code> (toString/valueOf)</td></tr>
<tr><th>ToPrimitive</th><td>Usually <code>"[object Uint8Array]"</code>; like Uint8Array</td><td>identity</td><td><code>
"light_&lt;PTR&gt;_&lt;FLAGS&gt;"</code> (toString/valueOf)</td></tr>
<tr><th>ToBoolean</th><td>true</td><td>false for NULL pointer, true otherwise</td><td>true</td></tr>
<tr><th>ToNumber</th><td>ToNumber(String(buffer)), usually ToNumber("[object Uint8Array]") = NaN</td><td>0 for NULL pointer, 1 otherwise</td><td>NaN</td></tr>
<tr><th>ToInteger</th><td>same as ToNumber; usually 0</td><td>same as ToNumber</td><td>0</td></tr>
<tr><th>ToInt32</th><td>same as ToNumber; usually 0</td><td>same as ToNumber</td><td>0</td></tr>
<tr><th>ToUint32</th><td>same as ToNumber; usually 0</td><td>same as ToNumber</td><td>0</td></tr>
<tr><th>ToUint16</th><td>same as ToNumber; usually 0</td><td>same as ToNumber</td><td>0</td></tr>
<tr><th>ToString</th><td>Usually <code>[object Uint8Array]</code>; like Uint8Array</td><td><code>sprintf()</code> with <code>%p</code> format (platform specific)</td><td><code>"light_&lt;PTR&gt;_&lt;FLAGS&gt;"</code></td></tr>
<tr><th>ToObject</th><td>Uint8Array object (backs to argument plain buffer)</td><td>Pointer object</td><td>Function object</td></tr>
<tr><th>CheckObjectCoercible</th><td>allow (no error)</td><td>allow (no error)</td><td>allow (no error)</td></tr>
<tr><th>IsCallable</th><td>false</td><td>false</td><td>true</td></tr>
<tr><th>SameValue</th><td>(covered above)</td><td>(covered above)</td><td>(covered above)</td></tr>
</tbody>
</table><p>When a buffer is string coerced it behaves like an Uint8Array, with the
result usually being <code>"[object Uint8Array]"</code>.  This behavior was
changed in Duktape 2.0.  To create a string from buffer contents you can use
e.g. the Node.js Buffer binding or the Encoding API.</p><p>When a buffer is object coerced a new Uint8Array object is created, with
a new ArrayBuffer backing to the plain buffer (no copy is made).</p><p>When a lightfunc is coerced with ToPrimitive() it behaves like an ordinary
function: it gets coerced with <code>Function.prototype.toString()</code> with
the result (normally) being the same as ToString() coercion.</p><p>When a lightfunc is object coerced, a new Function object is created
and the virtual properties (<code>name</code> and <code>length</code> and
the internal "magic" value are copied over to the Function object.</p><h2 class="sectiontitle" id="typealgorithms.6">Custom coercions (ToBuffer, ToPointer) <a class="sectionlink" href="#typealgorithms.6">§</a></h2><p>ToBuffer() coercion is used when a value is forced into a buffer
type e.g. with the <code>duk_to_buffer()</code> API call.  The coercion
is as follows:</p><ul>
<li>A buffer coerces to itself (identity).  The same buffer value is
    returned.</li>
<li>Any other type (including pointer and lightfunc) is first string coerced with
    <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-9.8">ToString</a>,
    and the resulting string is then copied, byte-by-byte, into a
    fixed-size buffer.</li>
</ul><p>ToPointer() coercion is used e.g. by the <code>duk_to_pointer()</code>
call.  The coercion is as follows:</p><ul>
<li>A pointer coerces to itself.</li>
<li>Heap-allocated types (string, object, buffer) coerce to a pointer value
    pointing to their <b>internal heap header</b>.  This pointer has only a
    diagnostic value.  Note, in particular, that the pointer returned for a
    buffer or a string <b>does not</b> point to the buffer/string data area.
    (This coercion is liable to change even in minor versions, avoid relying
    on it.)</li>
<li>Any other types (including number) coerce to a NULL pointer.</li>
<li>Lightfunc coerces to a NULL pointer.  This is the case because C function
    pointers cannot be coerced to a <code>void *</code> in a portable manner.</li>
</ul><p>The following table summarizes how different types are handled:</p><table>
<thead>
<tr><th> </th><th>ToBuffer</th><th>ToPointer</th></tr>
</thead>
<tbody>
<tr><th>undefined</th><td>buffer with "undefined"</td><td>NULL</td></tr>
<tr><th>null</th><td>buffer with "null"</td><td>NULL</td></tr>
<tr><th>boolean</th><td>buffer with "true" or "false"</td><td>NULL</td></tr>
<tr><th>number</th><td>buffer with string coerced number</td><td>NULL</td></tr>
<tr><th>string</th><td>buffer with copy of string data</td><td>ptr to heap hdr</td></tr>
<tr><th>object</th><td>buffer with ToString(value)</td><td>ptr to heap hdr</td></tr>
<tr><th>buffer</th><td>identity</td><td>ptr to heap hdr</td></tr>
<tr><th>pointer</th><td><code>sprintf()</code> with <code>%p</code> format (platform specific)</td><td>identity</td></tr>
<tr><th>lightfunc</th><td>buffer with ToString(value)</td><td>NULL</td></tr>
</tbody>
</table><div class="note">
There is currently no ToLightFunc() coercion.  Lightfuncs can only be created
using the Duktape C API.
</div><h2 class="sectiontitle" id="typealgorithms.7">Addition <a class="sectionlink" href="#typealgorithms.7">§</a></h2><p>The Ecmascript addition operator is specified in
<a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.6.1">The Addition operator (+)</a>.
Addition behaves specially if either argument is a string: the other argument
is coerced to a string and the strings are then concatenated.  This behavior
is extended to custom types as follows:</p><ul>
<li>As for standard types, object values are first coerced with <code>ToPrimitive()</code>;
    plain buffers and lightfuncs are normally coerced with <code>ToString()</code>.
    For plain buffers the result is usually <code>"[object Uint8Array]"</code>
    and for lightfuncs <code>"[object Function]"</code>.</li>
<li>Pointer values fall into the default number addition case.  They are coerced
    with <code>ToNumber()</code> and then added as numbers.  NULL pointers coerce to
    0, non-NULL pointers to 1, so addition results may not be very intuitive.</li>
</ul><p>Addition is not generally useful for custom types.  For example, if two plain
buffers are added, the result is usually <code>"[object Uint8Array][object Uint8Array]"</code>,
which matches how standard addition behaves for two Uint8Array instances.</p><h2 class="sectiontitle" id="typealgorithms.8">Property access <a class="sectionlink" href="#typealgorithms.8">§</a></h2><p>If a plain buffer or pointer is used as a property access base value,
properties are looked up from the (initial) built-in prototype object
(<code>Uint8Array.prototype</code> or <code>Duktape.Pointer.prototype</code>).
This mimics the behavior of standard types.</p><p>For example:</p><pre>
duk&gt; buf = Duktape.dec('hex', '414243');  // plain buffer
= ABC
duk&gt; buf.subarray();
= function subarray() {"native"}
duk&gt; typeof buf.toString();
= string
</pre><p>Lightfuncs have a few non-configurable and non-writable virtual properties
(<code>name</code> and <code>length</code>) and inherit their remaining
properties from <code>Function.prototype</code>, which allows ordinary inherited
Function methods to be called:</p><pre class="ecmascript-code"><span class="keyword">var</span><span class="normal"> bound </span><span class="symbol">=</span><span class="normal"> myLightFunc</span><span class="symbol">.</span><span class="function">bind</span><span class="symbol">(</span><span class="string">'dummy'</span><span class="symbol">,</span><span class="normal"> </span><span class="number">123</span><span class="symbol">);</span>
</pre><hr/><h1 class="sectiontitle" id="duktapebuiltins">Duktape built-ins <a class="sectionlink" href="#duktapebuiltins">§</a></h1><p>This section summarizes Duktape-specific and non-Ecmascript built-in
objects, methods, and values.</p><h2 class="sectiontitle" id="duktapebuiltins.1">Additional global object properties <a class="sectionlink" href="#duktapebuiltins.1">§</a></h2><table>
<thead>
<tr>
<th>Property</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="propname"><a href="#builtin-duktape">Duktape</a></td>
<td>The Duktape built-in object.  Contains miscellaneous implementation specific stuff.</td>
</tr>
<tr>
<td class="propname"><a href="#builtin-textencoder">TextEncoder</a></td>
<td>TextEncoder() from <a href="https://encoding.spec.whatwg.org/">WHATWG Encoding API</a>.
    Converts a string into a buffer using UTF-8 encoding.</td>
</tr>
<tr>
<td class="propname"><a href="#builtin-textdecoder">TextDecoder</a></td>
<td>TextDecoder() from <a href="https://encoding.spec.whatwg.org/">WHATWG Encoding API</a>.
    Converts a buffer into a string using UTF-8 encoding.</td>
</tr>
</tbody>
</table><h2 class="sectiontitle" id="builtin-duktape">The Duktape object <a class="sectionlink" href="#builtin-duktape">§</a></h2><table>
<thead>
<tr>
<th>Property</th><th>Description</th>
</tr>
</thead>
<tbody>
<tr><td class="propname"><a href="#builtin-duktape-version">version</a></td>
<td>Duktape version number: <code>(major * 10000) + (minor * 100) + patch</code>.</td></tr>
<tr><td class="propname"><a href="#builtin-duktape-env">env</a></td>
<td>Cryptic, version dependent summary of most important effective options like endianness and architecture.</td></tr>
<tr><td class="propname"><a href="#builtin-duktape-fin">fin</a></td>
<td>Set or get finalizer of an object.</td></tr>
<tr><td class="propname"><a href="#builtin-duktape-enc">enc</a></td>
<td>Encode a value (hex, base-64, JX, JC): <code>Duktape.enc('hex', 'foo')</code>.</td></tr>
<tr><td class="propname"><a href="#builtin-duktape-dec">dec</a></td>
<td>Decode a value (hex, base-64, JX, JC): <code>Duktape.dec('base64', 'Zm9v')</code>.</td></tr>
<tr><td class="propname"><a href="#builtin-duktape-info">info</a></td>
<td>Get internal information (such as heap address and alloc size)
        of a value in a version specific format.  The C API equivalent
        is <code>duk_inspect_value()</code>.</td></tr>
<tr><td class="propname"><a href="#builtin-duktape-act">act</a></td>
<td>Get information about call stack entry.</td></tr>
<tr><td class="propname"><a href="#builtin-duktape-gc">gc</a></td>
<td>Trigger mark-and-sweep garbage collection.</td></tr>
<tr><td class="propname"><a href="#builtin-duktape-compact">compact</a></td>
<td>Compact the memory allocated for a value (object).</td></tr>
<tr><td class="propname"><a href="#builtin-duktape-errcreate-errthrow">errCreate</a></td>
<td>Callback to modify/replace a created error.</td></tr>
<tr><td class="propname"><a href="#builtin-duktape-errcreate-errthrow">errThrow</a></td>
<td>Callback to modify/replace an error about to be thrown.</td></tr>
<tr><td class="propname"><a href="#builtin-duktape-pointer">Pointer</a></td>
<td>Pointer constructor (function).</td></tr>
<tr><td class="propname"><a href="#builtin-duktape-thread">Thread</a></td>
<td>Thread constructor (function).</td></tr>
</tbody>
</table><h3 class="sectiontitle" id="builtin-duktape-version">version <a class="sectionlink" href="#builtin-duktape-version">§</a></h3><p>The <code>version</code> property allows version-based feature detection and
behavior.  Version numbers can be compared directly: a logically higher version
will also be numerically higher.  For example:</p><pre class="ecmascript-code"><span class="keyword">if</span><span class="normal"> </span><span class="symbol">(</span><span class="keyword">typeof</span><span class="normal"> Duktape </span><span class="symbol">!==</span><span class="normal"> </span><span class="string">'object'</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="function">print</span><span class="symbol">(</span><span class="string">'not Duktape'</span><span class="symbol">);</span>
<span class="cbracket">}</span><span class="normal"> </span><span class="keyword">else</span><span class="normal"> </span><span class="keyword">if</span><span class="normal"> </span><span class="symbol">(</span><span class="normal">Duktape</span><span class="symbol">.</span><span class="normal">version </span><span class="symbol">&gt;=</span><span class="normal"> </span><span class="number">10203</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="function">print</span><span class="symbol">(</span><span class="string">'Duktape 1.2.3 or higher'</span><span class="symbol">);</span>
<span class="cbracket">}</span><span class="normal"> </span><span class="keyword">else</span><span class="normal"> </span><span class="keyword">if</span><span class="normal"> </span><span class="symbol">(</span><span class="normal">Duktape</span><span class="symbol">.</span><span class="normal">version </span><span class="symbol">&gt;=</span><span class="normal"> </span><span class="number">800</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="function">print</span><span class="symbol">(</span><span class="string">'Duktape 0.8.0 or higher (but lower than 1.2.3)'</span><span class="symbol">);</span>
<span class="cbracket">}</span><span class="normal"> </span><span class="keyword">else</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="function">print</span><span class="symbol">(</span><span class="string">'Duktape lower than 0.8.0'</span><span class="symbol">);</span>
<span class="cbracket">}</span>
</pre><p>The value of <code>version</code> for pre-releases is one less than the
actual release, e.g. 1199 for a 0.12.0 pre-release and 10299 for a 1.3.0
pre-release.  See <a href="#versioning">Versioning</a>.</p><p>Remember to check for existence of <code>Duktape</code> when doing feature
detection.  Your code should typically work on as many engines as possible.
Avoid the common pitfall of using a direct identifier reference in the check:</p><pre class="ecmascript-code"><span class="comment">// Bad idea: ReferenceError if missing</span>
<span class="keyword">if</span><span class="normal"> </span><span class="symbol">(!</span><span class="normal">Duktape</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="function">print</span><span class="symbol">(</span><span class="string">'not Duktape'</span><span class="symbol">);</span>
<span class="cbracket">}</span>

<span class="comment">// Better: check through 'this' (bound to global)</span>
<span class="keyword">if</span><span class="normal"> </span><span class="symbol">(!</span><span class="keyword">this</span><span class="symbol">.</span><span class="normal">Duktape</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="function">print</span><span class="symbol">(</span><span class="string">'not Duktape'</span><span class="symbol">);</span>
<span class="cbracket">}</span>

<span class="comment">// Better: use typeof to check also type explicitly</span>
<span class="keyword">if</span><span class="normal"> </span><span class="symbol">(</span><span class="keyword">typeof</span><span class="normal"> Duktape </span><span class="symbol">!==</span><span class="normal"> </span><span class="string">'object'</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="function">print</span><span class="symbol">(</span><span class="string">'not Duktape'</span><span class="symbol">);</span>
<span class="cbracket">}</span>
</pre><h3 class="sectiontitle" id="builtin-duktape-env">env <a class="sectionlink" href="#builtin-duktape-env">§</a></h3><p><code>env</code> summarizes the most important effective compile options
in a version specific, quite cryptic manner.  The format is version specific
and is not intended to be parsed programmatically.  This is mostly useful for
developers (see <code>duk_hthread_builtins.c</code> for the code which sets
the value).</p><p>Example from Duktape 1.1.0:</p><pre class="ecmascript-code"><span class="normal">ll u n p2 a4 x64 linux gcc     </span><span class="comment">// l|b|m integer endianness, l|b|m IEEE double endianness</span>
<span class="normal">                               </span><span class="comment">// p|u packed/unpacked tval</span>
<span class="normal">                               </span><span class="comment">// n|various, memory optimization options (n = none)</span>
<span class="normal">                               </span><span class="comment">// p1|p2|p3 prop memory layout</span>
<span class="normal">                               </span><span class="comment">// a1|a4|a8: align target</span>
<span class="normal">                               </span><span class="comment">// x64|x86|arm|etc: architecture</span>
<span class="normal">                               </span><span class="comment">// linux|windows|etc: operating system</span>
<span class="normal">                               </span><span class="comment">// gcc|clang|msvc|etc: compiler</span>
</pre><h3 class="sectiontitle" id="builtin-duktape-fin">fin() <a class="sectionlink" href="#builtin-duktape-fin">§</a></h3><p>When called with a single argument, gets the current finalizer of an object:</p><pre class="ecmascript-code"><span class="keyword">var</span><span class="normal"> currFin </span><span class="symbol">=</span><span class="normal"> Duktape</span><span class="symbol">.</span><span class="function">fin</span><span class="symbol">(</span><span class="normal">o</span><span class="symbol">);</span>
</pre><p>When called with two arguments, sets the finalizer of an object (returns undefined):</p><pre class="ecmascript-code"><span class="normal">Duktape</span><span class="symbol">.</span><span class="function">fin</span><span class="symbol">(</span><span class="normal">o</span><span class="symbol">,</span><span class="normal"> </span><span class="keyword">function</span><span class="symbol">(</span><span class="normal">x</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span><span class="normal"> </span><span class="function">print</span><span class="symbol">(</span><span class="string">'finalizer called'</span><span class="symbol">);</span><span class="normal"> </span><span class="cbracket">}</span><span class="symbol">);</span>
<span class="normal">Duktape</span><span class="symbol">.</span><span class="function">fin</span><span class="symbol">(</span><span class="normal">o</span><span class="symbol">,</span><span class="normal"> undefined</span><span class="symbol">);</span><span class="normal">  </span><span class="comment">// disable</span>
</pre><h3 class="sectiontitle" id="builtin-duktape-enc">enc() <a class="sectionlink" href="#builtin-duktape-enc">§</a></h3><p><code>enc()</code> encodes its argument value into chosen format.
The first argument is a format (currently supported are "hex", "base64",
"jx" and "jc"), second argument is the value to encode, and any further
arguments are format specific.</p><!-- XXX: maybe remove support for non-buffer inputs? --><p>For "hex" and "base64", buffer values are encoded as is, other values
are string coerced and the internal byte representation (extended UTF-8)
is then encoded.  The result is a string.  For example, to encode a string
into base64:</p><pre class="ecmascript-code"><span class="keyword">var</span><span class="normal"> result </span><span class="symbol">=</span><span class="normal"> Duktape</span><span class="symbol">.</span><span class="function">enc</span><span class="symbol">(</span><span class="string">'base64'</span><span class="symbol">,</span><span class="normal"> </span><span class="string">'foo'</span><span class="symbol">);</span>
<span class="function">print</span><span class="symbol">(</span><span class="normal">result</span><span class="symbol">);</span><span class="normal">  </span><span class="comment">// prints 'Zm9v'</span>
</pre><p>For "jx" and "jc" the argument list following the format name is the
same as for <code>JSON.stringify()</code>: value, replacer (optional),
space (optional).  For example:</p><pre class="ecmascript-code"><span class="keyword">var</span><span class="normal"> result </span><span class="symbol">=</span><span class="normal"> Duktape</span><span class="symbol">.</span><span class="function">enc</span><span class="symbol">(</span><span class="string">'jx'</span><span class="symbol">,</span><span class="normal"> </span><span class="cbracket">{</span><span class="normal"> foo</span><span class="symbol">:</span><span class="normal"> </span><span class="number">123</span><span class="normal"> </span><span class="cbracket">}</span><span class="symbol">,</span><span class="normal"> </span><span class="keyword">null</span><span class="symbol">,</span><span class="normal"> </span><span class="number">4</span><span class="symbol">);</span>
<span class="function">print</span><span class="symbol">(</span><span class="normal">result</span><span class="symbol">);</span><span class="normal">  </span><span class="comment">// prints JX encoded {foo:123} with 4-space indent</span>
</pre><h3 class="sectiontitle" id="builtin-duktape-dec">dec() <a class="sectionlink" href="#builtin-duktape-dec">§</a></h3><p><code>dec()</code> provides the reverse function of <code>enc()</code>.</p><p>For "hex" and "base64" the input value is first string coerced (it only
really makes sense to decode strings).  The result is always a plain buffer.
For example:</p><pre class="ecmascript-code"><span class="keyword">var</span><span class="normal"> result </span><span class="symbol">=</span><span class="normal"> Duktape</span><span class="symbol">.</span><span class="function">dec</span><span class="symbol">(</span><span class="string">'base64'</span><span class="symbol">,</span><span class="normal"> </span><span class="string">'Zm9v'</span><span class="symbol">);</span>
<span class="function">print</span><span class="symbol">(</span><span class="keyword">typeof</span><span class="normal"> result</span><span class="symbol">,</span><span class="normal"> result</span><span class="symbol">);</span><span class="normal">  </span><span class="comment">// prints 'object foo'</span>
</pre><p>If you prefer a full <code>Uint8Array</code> over a plain buffer, you can
coerce the result as follows:</p><pre class="ecmascript-code"><span class="keyword">var</span><span class="normal"> result </span><span class="symbol">=</span><span class="normal"> </span><span class="function">Object</span><span class="symbol">(</span><span class="normal">Duktape</span><span class="symbol">.</span><span class="function">dec</span><span class="symbol">(</span><span class="string">'base64'</span><span class="symbol">,</span><span class="normal"> </span><span class="string">'Zm9v'</span><span class="symbol">));</span>
<span class="function">print</span><span class="symbol">(</span><span class="keyword">typeof</span><span class="normal"> result</span><span class="symbol">,</span><span class="normal"> result</span><span class="symbol">);</span><span class="normal">  </span><span class="comment">// prints 'object foo'</span>
</pre><p>If you wish to get back a string value, you can coerce the plain buffer to
a string e.g. as follows:</p><pre class="ecmascript-code"><span class="comment">// Use TextDecoder which decodes the input as UTF-8.  You can also use</span>
<span class="comment">// the Node.js Buffer binding to achieve a similar result.</span>

<span class="keyword">var</span><span class="normal"> result </span><span class="symbol">=</span><span class="normal"> </span><span class="keyword">new</span><span class="normal"> </span><span class="function">TextDecoder</span><span class="symbol">().</span><span class="function">decode</span><span class="symbol">(</span><span class="normal">Duktape</span><span class="symbol">.</span><span class="function">dec</span><span class="symbol">(</span><span class="string">'base64'</span><span class="symbol">,</span><span class="normal"> </span><span class="string">'Zm9v'</span><span class="symbol">));</span>
<span class="function">print</span><span class="symbol">(</span><span class="keyword">typeof</span><span class="normal"> result</span><span class="symbol">,</span><span class="normal"> result</span><span class="symbol">);</span><span class="normal">  </span><span class="comment">// prints 'string foo'</span>
</pre><p>For "jx" and "jc" the argument list following the format name is the same
as for <code>JSON.parse()</code>: text, reviver (optional).  For example:</p><pre class="ecmascript-code"><span class="keyword">var</span><span class="normal"> result </span><span class="symbol">=</span><span class="normal"> Duktape</span><span class="symbol">.</span><span class="function">dec</span><span class="symbol">(</span><span class="string">'jx'</span><span class="symbol">,</span><span class="normal"> </span><span class="string">"{foo:123}"</span><span class="symbol">);</span>
<span class="function">print</span><span class="symbol">(</span><span class="normal">result</span><span class="symbol">.</span><span class="normal">foo</span><span class="symbol">);</span><span class="normal">  </span><span class="comment">// prints 123</span>
</pre><h3 class="sectiontitle" id="builtin-duktape-info">info() <a class="sectionlink" href="#builtin-duktape-info">§</a></h3><p><code>Duktape.info()</code> returns an object exposing internal information
related to its argument value.  See
<code><a href="api.html#duk_inspect_value">duk_inspect_value()</a></code>
for description of current fields.</p><div class="note">
The properties of the result object are not under versioning guarantees and may
change in an incompatible fashion even in minor versions (but not patch versions).
</div><h3 class="sectiontitle" id="builtin-duktape-act">act() <a class="sectionlink" href="#builtin-duktape-act">§</a></h3><p>Get information about a call stack entry.  Takes a single number argument
indicating depth in the call stack: -1 is the top (innermost) entry, -2 is the
one below that etc.  Returns an object describing the call stack entry, or
<code>undefined</code> if the entry doesn't exist.  See
<code><a href="api.html#duk_inspect_callstack_entry">duk_inspect_callstack_entry()</a></code>
for description of current fields.</p><div class="note">
The properties of the result object are not under versioning guarantees and may
change in an incompatible fashion even in minor versions (but not patch versions).
</div><p>Example:</p><pre class="ecmascript-code"><span class="keyword">function</span><span class="normal"> </span><span class="function">dump</span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="keyword">var</span><span class="normal"> i</span><span class="symbol">,</span><span class="normal"> t</span><span class="symbol">;</span>
<span class="normal">    </span><span class="keyword">for</span><span class="normal"> </span><span class="symbol">(</span><span class="normal">i </span><span class="symbol">=</span><span class="normal"> </span><span class="symbol">-</span><span class="number">1</span><span class="symbol">;</span><span class="normal"> </span><span class="symbol">;</span><span class="normal"> i</span><span class="symbol">--)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">        t </span><span class="symbol">=</span><span class="normal"> Duktape</span><span class="symbol">.</span><span class="function">act</span><span class="symbol">(</span><span class="normal">i</span><span class="symbol">);</span>
<span class="normal">        </span><span class="keyword">if</span><span class="normal"> </span><span class="symbol">(!</span><span class="normal">t</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span><span class="normal"> </span><span class="keyword">break</span><span class="symbol">;</span><span class="normal"> </span><span class="cbracket">}</span>
<span class="normal">        </span><span class="function">print</span><span class="symbol">(</span><span class="normal">i</span><span class="symbol">,</span><span class="normal"> t</span><span class="symbol">.</span><span class="normal">lineNumber</span><span class="symbol">,</span><span class="normal"> t</span><span class="symbol">.</span><span class="keyword">function</span><span class="symbol">.</span><span class="normal">name</span><span class="symbol">,</span><span class="normal"> Duktape</span><span class="symbol">.</span><span class="function">enc</span><span class="symbol">(</span><span class="string">'jx'</span><span class="symbol">,</span><span class="normal"> t</span><span class="symbol">));</span>
<span class="normal">    </span><span class="cbracket">}</span>
<span class="cbracket">}</span>

<span class="function">dump</span><span class="symbol">();</span>
</pre><p>The example, when executed with the command line tool, currently prints
something like:</p><pre>
-1 0 act {lineNumber:0,pc:0,function:{_func:true}}
-2 4 dump {lineNumber:4,pc:16,function:{_func:true}}
-3 10 global {lineNumber:10,pc:5,function:{_func:true}}
</pre><p>The interesting entries are <code>lineNumber</code> and <code>function</code>
which provides e.g. the function name.</p><p>You can also implement a helper to get the current line number using
<code>Duktape.act()</code>:</p><pre class="ecmascript-code"><span class="keyword">function</span><span class="normal"> </span><span class="function">getCurrentLine</span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="string">'use duk notail'</span><span class="symbol">;</span>

<span class="normal">    </span><span class="comment">/* Tail calls are prevented to ensure calling activation exists.</span>
<span class="comment">     * Call stack indices: -1 = Duktape.act, -2 = getCurrentLine, -3 = caller</span>
<span class="comment">     */</span>

<span class="normal">    </span><span class="keyword">var</span><span class="normal"> a </span><span class="symbol">=</span><span class="normal"> Duktape</span><span class="symbol">.</span><span class="function">act</span><span class="symbol">(-</span><span class="number">3</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">||</span><span class="normal"> </span><span class="cbracket">{}</span><span class="symbol">;</span>
<span class="normal">    </span><span class="keyword">return</span><span class="normal"> a</span><span class="symbol">.</span><span class="normal">lineNumber</span><span class="symbol">;</span>
<span class="cbracket">}</span>
<span class="function">print</span><span class="symbol">(</span><span class="string">'running on line:'</span><span class="symbol">,</span><span class="normal"> </span><span class="function">getCurrentLine</span><span class="symbol">());</span>
</pre><h3 class="sectiontitle" id="builtin-duktape-gc">gc() <a class="sectionlink" href="#builtin-duktape-gc">§</a></h3><p>Trigger a forced mark-and-sweep collection.  The call takes an optional
integer flags field, see <code>duktape.h</code> for constants.</p><!-- Return value is undocumented for now, which is probably good for now.
     Not sure what the best return value would be.
--><h3 class="sectiontitle" id="builtin-duktape-compact">compact() <a class="sectionlink" href="#builtin-duktape-compact">§</a></h3><p>Minimize the memory allocated for a target object.  Same as the C API call
<code>duk_compact()</code> but accessible from Ecmascript code.  If called with
a non-object argument, this call is a no-op.  The argument value is returned by
the function, which allows code such as:</p><pre class="ecmascript-code"><span class="keyword">var</span><span class="normal"> obj </span><span class="symbol">=</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    foo</span><span class="symbol">:</span><span class="normal"> Duktape</span><span class="symbol">.</span><span class="function">compact</span><span class="symbol">(</span><span class="cbracket">{</span><span class="normal"> bar</span><span class="symbol">:</span><span class="number">123</span><span class="normal"> </span><span class="cbracket">}</span><span class="symbol">)</span>
<span class="cbracket">}</span>
</pre><p>This call is useful when you know that an object is unlikely to gain new
properties, but you don't want to seal or freeze the object in case it does.</p><h3 class="sectiontitle" id="builtin-duktape-errcreate-errthrow">errCreate() and errThrow() <a class="sectionlink" href="#builtin-duktape-errcreate-errthrow">§</a></h3><p>These can be set by user code to process/replace errors when they are created
(<code>errCreate</code>) or thrown (<code>errThrow</code>).  Both values are
initially non-existent.</p><p>See
<a href="#error-handlers">Error handlers (errCreate and errThrow)</a> for
details.</p><h2 class="sectiontitle" id="builtin-duktape-pointer">Duktape.Pointer (constructor) <a class="sectionlink" href="#builtin-duktape-pointer">§</a></h2><table>
<thead>
<tr>
<th>Property</th><th>Description</th>
</tr>
</thead>
<tbody>
<tr><td class="propname">prototype</td><td>Prototype for Pointer objects.</td></tr>
</tbody>
</table><p>The Pointer constructor is a function which can be called both as an
ordinary function and as a constructor:</p><ul>
<li>When called as a function, coerces the first argument to a pointer using
    the custom <code>ToPointer</code> coercion.  The return value is a plain
    pointer (not a Pointer object).</li>
<li>When called as a constructor, coerces the first argument to a pointer
    using the custom <code>ToPointer</code> coercion.  Returns a Pointer object
    whose internal value is the pointer resulting from the coercion.  The
    internal prototype of the newly created Pointer will be the
    <code>Duktape.Pointer.prototype</code> object.</li>
</ul><h2 class="sectiontitle" id="duktapebuiltins.4">Duktape.Pointer.prototype <a class="sectionlink" href="#duktapebuiltins.4">§</a></h2><table>
<thead>
<tr>
<th>Property</th><th>Description</th>
</tr>
</thead>
<tbody>
<tr><td class="propname">toString</td><td>Convert Pointer to a printable string.</td></tr>
<tr><td class="propname">valueOf</td><td>Return the primitive pointer value held by Pointer.</td></tr>
</tbody>
</table><p><code>toString()</code> and <code>valueOf</code> accept both plain pointers and
Pointer objects as their <code>this</code> binding.  This allows code such as:</p><pre class="ecmascript-code"><span class="keyword">var</span><span class="normal"> plain_ptr </span><span class="symbol">=</span><span class="normal"> Duktape</span><span class="symbol">.</span><span class="function">Pointer</span><span class="symbol">(</span><span class="cbracket">{</span><span class="normal"> test</span><span class="symbol">:</span><span class="normal"> </span><span class="string">'object'</span><span class="normal"> </span><span class="cbracket">}</span><span class="symbol">);</span>
<span class="function">print</span><span class="symbol">(</span><span class="normal">plain_ptr</span><span class="symbol">.</span><span class="function">toString</span><span class="symbol">());</span>
</pre><h2 class="sectiontitle" id="builtin-duktape-thread">Duktape.Thread (constructor) <a class="sectionlink" href="#builtin-duktape-thread">§</a></h2><table>
<thead>
<tr>
<th>Property</th><th>Description</th>
</tr>
</thead>
<tbody>
<tr><td class="propname">prototype</td><td>Prototype for Thread objects.</td></tr>
<tr><td class="propname">resume</td><td>Resume target thread with a value or an error.
Arguments: target thread, value, flag indicating whether value is to be thrown (optional, default false).</td></tr>
<tr><td class="propname">yield</td><td>Yield a value or an error from current thread.
Arguments: value, flag indicating whether value is to be thrown (optional, default false).</td></tr>
<tr><td class="propname">current</td><td>Get currently running Thread object.</td></tr>
</tbody>
</table><p>The Thread constructor is a function which can be called both as an
ordinary function and as a constructor.  The behavior is the same in both
cases:</p><ul>
<li>The first argument is checked to be a function (if not, a <code>TypeError</code>
    is thrown).  The function must be an Ecmascript function (bound or non-bound).
    The return value is a new thread whose initial function is recorded to be the
    argument function (this function will start executing when the new thread is
    first resumed).  The internal prototype of the newly created Thread will be the
    <code>Duktape.Thread.prototype</code> object.</li>
</ul><h2 class="sectiontitle" id="duktapebuiltins.6">Duktape.Thread.prototype <a class="sectionlink" href="#duktapebuiltins.6">§</a></h2><table>
<thead>
<tr>
<th>Property</th><th>Description</th>
</tr>
</thead>
<tbody>
<tr><td colspan="2">No properties at the moment.</td></tr>
</tbody>
</table><h2 class="sectiontitle" id="builtin-textencoder">TextEncoder <a class="sectionlink" href="#builtin-textencoder">§</a></h2><p>TextEncoder() is part of the <a href="https://encoding.spec.whatwg.org/">WHATWG Encoding API</a>
and provides a clean way of encoding a string into a buffer (Uint8Array)
using UTF-8 encoding.  Surrogate pairs are combined during the process.
For example:</p><pre class="ecmascript-code"><span class="keyword">var</span><span class="normal"> str </span><span class="symbol">=</span><span class="normal"> </span><span class="string">'</span><span class="specialchar">\u</span><span class="string">{1f4a9}'</span><span class="symbol">;</span><span class="normal">                   </span><span class="comment">// non-BMP codepoint</span>
<span class="function">print</span><span class="symbol">(</span><span class="normal">str</span><span class="symbol">.</span><span class="normal">length</span><span class="symbol">);</span><span class="normal">                       </span><span class="comment">// length is 2, represented as a surrogate pair</span>
<span class="keyword">var</span><span class="normal"> u8 </span><span class="symbol">=</span><span class="normal"> </span><span class="keyword">new</span><span class="normal"> </span><span class="function">TextEncoder</span><span class="symbol">().</span><span class="function">encode</span><span class="symbol">(</span><span class="normal">str</span><span class="symbol">);</span>
<span class="function">print</span><span class="symbol">(</span><span class="normal">u8</span><span class="symbol">.</span><span class="normal">length</span><span class="symbol">);</span><span class="normal">                        </span><span class="comment">// length is 4, a single UTF-8 codepoint</span>
<span class="function">print</span><span class="symbol">(</span><span class="normal">Duktape</span><span class="symbol">.</span><span class="function">enc</span><span class="symbol">(</span><span class="string">'jx'</span><span class="symbol">,</span><span class="normal"> u8</span><span class="symbol">));</span><span class="normal">            </span><span class="comment">// |f09f92a9|, UTF-8 bytes F0 9F 92 A9</span>
</pre><h2 class="sectiontitle" id="builtin-textdecoder">TextDecoder <a class="sectionlink" href="#builtin-textdecoder">§</a></h2><p>TextDecoder() is part of the <a href="https://encoding.spec.whatwg.org/">WHATWG Encoding API</a>
and provides a clean way of decoding a buffer into a string using UTF-8
encoding.  Non-BMP codepoints are represented as surrogate pairs in the
resulting string.  For example:</p><pre class="ecmascript-code"><span class="keyword">var</span><span class="normal"> u8 </span><span class="symbol">=</span><span class="normal"> </span><span class="keyword">new</span><span class="normal"> </span><span class="function">Uint8Array</span><span class="symbol">([</span><span class="normal"> </span><span class="number">0xf0</span><span class="symbol">,</span><span class="normal"> </span><span class="number">0x9f</span><span class="symbol">,</span><span class="normal"> </span><span class="number">0x92</span><span class="symbol">,</span><span class="normal"> </span><span class="number">0xa9</span><span class="normal"> </span><span class="symbol">]);</span><span class="normal">  </span><span class="comment">// a single non-BMP codepoint</span>
<span class="keyword">var</span><span class="normal"> str </span><span class="symbol">=</span><span class="normal"> </span><span class="keyword">new</span><span class="normal"> </span><span class="function">TextDecoder</span><span class="symbol">().</span><span class="function">decode</span><span class="symbol">(</span><span class="normal">u8</span><span class="symbol">);</span>
<span class="function">print</span><span class="symbol">(</span><span class="normal">str</span><span class="symbol">.</span><span class="normal">length</span><span class="symbol">);</span><span class="normal">                       </span><span class="comment">// length is 2, represented as a surrogate pair</span>
<span class="function">print</span><span class="symbol">(</span><span class="normal">str</span><span class="symbol">.</span><span class="function">charCodeAt</span><span class="symbol">(</span><span class="number">0</span><span class="symbol">));</span><span class="normal">                </span><span class="comment">// 55357, high surrogate</span>
<span class="function">print</span><span class="symbol">(</span><span class="normal">str</span><span class="symbol">.</span><span class="function">charCodeAt</span><span class="symbol">(</span><span class="number">1</span><span class="symbol">));</span><span class="normal">                </span><span class="comment">// 56489, low surrogate</span>
</pre><a name="es6features"></a><a name="es6-regexp-syntax"></a><a name="es6-const"></a><a name="es6-computed-property-names"></a><a name="es6-number-literals"></a><a name="es6-unicode-escape"></a><a name="es6-proto"></a><a name="es6-reflect"></a><a name="es6-proxy"></a><a name="es6-typedarray"></a><a name="es6-enum-order"></a><a name="es7features"></a><a name="es7-exp-operator"></a><hr/><h1 class="sectiontitle" id="postes5features">Post-ES5 features <a class="sectionlink" href="#postes5features">§</a></h1><p>Duktape implements features from ES2015 (ES6), ES2016 (ES7), and later
specification drafts.  See Wiki article
<a href="http://wiki.duktape.org/PostEs5Features.html">Post-ES5 features</a>
for current status.</p><hr/><h1 class="sectiontitle" id="custombehavior">Custom behavior <a class="sectionlink" href="#custombehavior">§</a></h1><p>This section summarizes Duktape behavior which deviates from the E5.1 or
other relevant specifications.</p><h2 class="sectiontitle" id="custombehavior.1">Duktape built-in and custom types <a class="sectionlink" href="#custombehavior.1">§</a></h2><p>The <code>Duktape</code> built-in is (of course) non-standard and provides
access to Duktape specific features.  Also the buffer, pointer, and lightfunc
types are custom.</p><h2 class="sectiontitle" id="custombehavior.2">Hidden Symbols <a class="sectionlink" href="#custombehavior.2">§</a></h2><p>Objects may have properties with <a href="#symbols">hidden Symbol</a> keys.
These are similar to ES2015 Symbols but won't be enumerated or returned from even
<code>Object.getOwnPropertySymbols()</code>.  Ordinary Ecmascript code cannot
refer to such properties because the keys intentionally use an invalid (extended)
UTF-8 representation.</p><h2 class="sectiontitle" id="custombehavior.3">"use duk notail" directive <a class="sectionlink" href="#custombehavior.3">§</a></h2><p>The <a href="#use-duk-notail">"use duk notail"</a> directive is non-standard.
It prevents a function from being tail called.</p><h2 class="sectiontitle" id="custombehavior.4">"const" treated mostly like "var" <a class="sectionlink" href="#custombehavior.4">§</a></h2><p>The <code>const</code> keyword is supported with minimal non-standard
semantics (officially defined in Ecmascript 6).  See
<a href="#es6-const">Const variables</a> for more detail.</p><h2 class="sectiontitle" id="custombehavior.5">Additional Error and Function object properties <a class="sectionlink" href="#custombehavior.5">§</a></h2><p>See
<a href="#errorobjects">Error objects</a> and
<a href="functionobjects">Function objects</a>.</p><p>Non-strict function instances don't have a <code>caller</code> property in the
E5/E5.1 specification.  Some real world code expects to have this property, so it
can be enabled with the config option <code>DUK_USE_NONSTD_FUNC_CALLER_PROPERTY</code>.</p><h2 class="sectiontitle" id="custombehavior.6">Function statements <a class="sectionlink" href="#custombehavior.6">§</a></h2><p>E5.1 does not allow a function declaration to appear outside program or
function top level:</p><pre class="ecmascript-code"><span class="keyword">function</span><span class="normal"> </span><span class="function">test</span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="comment">// point A</span>
<span class="normal">    </span><span class="keyword">try</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">        </span><span class="keyword">throw</span><span class="normal"> </span><span class="keyword">new</span><span class="normal"> </span><span class="function">Error</span><span class="symbol">(</span><span class="string">'test'</span><span class="symbol">);</span>
<span class="normal">    </span><span class="cbracket">}</span><span class="normal"> </span><span class="keyword">catch</span><span class="normal"> </span><span class="symbol">(</span><span class="normal">e</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">        </span><span class="comment">// This is a SyntaxError in E5.1</span>
<span class="normal">        </span><span class="keyword">function</span><span class="normal"> </span><span class="function">func</span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">            </span><span class="function">print</span><span class="symbol">(</span><span class="keyword">typeof</span><span class="normal"> e</span><span class="symbol">);</span>
<span class="normal">        </span><span class="cbracket">}</span>
<span class="normal">        </span><span class="comment">// point B</span>
<span class="normal">    </span><span class="cbracket">}</span>
<span class="normal">    </span><span class="comment">// point C</span>
<span class="cbracket">}</span>
</pre><p>These declarations are also referred to as "function statements", and appear
quite often in real world code (including the test262 test suite), so they are
allowed by Duktape.  Unfortunately there are several semantics used by different
Javascript engines (<a href="http://www.ecma-international.org/ecma-262/6.0/index.html#sec-block-level-function-declarations-web-legacy-compatibility-semantics">ES2015</a>
unfortunately doesn't specify semantics for function statements either).
Duktape follows the V8 behavior for function statements:</p><ul>
<li>Strict function: a SyntaxError is thrown (standard behavior).</li>
<li>Non-strict function: treat a function statement like an ordinary function
    declaration, conceptually "hoisting" it to the top of the function.</li>
</ul><p>As an illustration, the above example would behave as the following:</p><pre class="ecmascript-code"><span class="keyword">function</span><span class="normal"> </span><span class="function">test</span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="keyword">function</span><span class="normal"> </span><span class="function">func</span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">        </span><span class="function">print</span><span class="symbol">(</span><span class="keyword">typeof</span><span class="normal"> e</span><span class="symbol">);</span>
<span class="normal">    </span><span class="cbracket">}</span>
<span class="normal"> </span>
<span class="normal">    </span><span class="keyword">try</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">        </span><span class="keyword">throw</span><span class="normal"> </span><span class="keyword">new</span><span class="normal"> </span><span class="function">Error</span><span class="symbol">(</span><span class="string">'test'</span><span class="symbol">);</span>
<span class="normal">    </span><span class="cbracket">}</span><span class="normal"> </span><span class="keyword">catch</span><span class="normal"> </span><span class="symbol">(</span><span class="normal">e</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="cbracket">}</span>
<span class="cbracket">}</span>
</pre><p><code>func()</code> in the above example would already be declared
and callable in point A, and would not have access to the <code>e</code>
binding in any of the points A, B, or C.</p><h2 class="sectiontitle" id="custombehavior.7">RegExp leniency <a class="sectionlink" href="#custombehavior.7">§</a></h2><p>Most Ecmascript engines support more syntax than guaranteed by the
<a href="http://www.ecma-international.org/ecma-262/5.1/#sec-15.10.1">Ecmascript
E5.1 specification (Section 15.10.1 Patterns)</a>.  As a result there's quite
a lot of code that won't work with strict Ecmascript E5.1 regexp syntax.  Much
of the additional syntax expected of web browser engines is documented in
<a href="http://www.ecma-international.org/ecma-262/6.0/#sec-regular-expressions-patterns">ES2015 Annex B.1.4 Regular Expression Patterns</a>.
However, note that features in
<a href="http://www.ecma-international.org/ecma-262/6.0/#sec-additional-ecmascript-features-for-web-browsers">Annex B Additional ECMAScript Features for Web Browsers</a> are
not recommended for new code:
"These features are not considered part of the core ECMAScript language.
Programmers should not use or assume the existence of these features and
behaviours when writing new ECMAScript code. ECMAScript implementations
are discouraged from implementing these features unless the implementation
is part of a web browser or is required to run the same legacy ECMAScript
code that web browsers encounter."</p><p>Duktape also allows some ES2015 Annex B syntax to better support existing
code.  You can turn this non-standard behavior off using config options if
you prefer.  Some examples of additional syntax supported:</p><pre>
  /{(\d+)}/    // unescaped left curly, digits, unescaped right curly; ES2015 Annex B
  /\{(\d+)\}/  // same, ES5 compliant

  /]/          // unescaped right bracket; ES2015 Annex B
  /\]/         // same, ES5 compliant

  /\$/         // literal dollar using escape; ES2015 Annex B
  /\u0024/     // same, ES5 compliant
</pre><h2 class="sectiontitle" id="custombehavior.8">Array.prototype.splice() when deleteCount not given <a class="sectionlink" href="#custombehavior.8">§</a></h2><p>When deleteCount (the 2nd argument) is not given to <code>Array.prototype.splice()</code>,
the standard behavior is to work as if the 2nd argument was <code>undefined</code>
(or 0, which has the same behavior after coercions).  A more real world compatible
behavior is to treat the missing argument like positive infinity, i.e. to extend
the splice operation to the end of the array.</p><p>Because the non-standard real world behavior is expected by much existing code,
Duktape uses this behavior by default.  The strict standards compliant behavior can
be enabled by disabling the config option <code>DUK_USE_NONSTD_ARRAY_SPLICE_DELCOUNT</code>.</p><h2 class="sectiontitle" id="custombehavior.9">Array.prototype.concat() trailing non-existent elements <a class="sectionlink" href="#custombehavior.9">§</a></h2><p>When the result of an array <code>concat()</code> would have trailing non-existent
elements, the standard behavior is to ignore them so that they are not reflected in
the result <code>length</code>.  Real world behavior is to include them in the result
value <code>length</code>.  See
<a href="https://github.com/svaarala/duktape/blob/master/tests/ecmascript/test-bi-array-proto-concat-nonstd-trailing.js">test-bi-array-proto-concat-nonstd-trailing.js</a>.</p><p>The real world behavior seems consistent in other engines (V8, Rhino, Spidermonkey
at least), so Duktape uses the real world behavior by default.  The strict standards compliant
behavior can be enabled by disabling the config option <code>DUK_USE_NONSTD_ARRAY_CONCAT_TRAILER</code>.</p><h2 class="sectiontitle" id="custombehavior.10">Array.prototype.map() trailing non-existent elements <a class="sectionlink" href="#custombehavior.10">§</a></h2><p>Similar issue as with <code>Array.prototype.concat()</code>, see
<a href="https://github.com/svaarala/duktape/blob/master/tests/ecmascript/test-bi-array-proto-map-nonstd-trailing.js">test-bi-array-proto-map-nonstd-trailing.js</a>.  The strict standards compliant behavior can be
enabled by disabling the config option <code>DUK_USE_NONSTD_ARRAY_MAP_TRAILER</code>.</p><h2 class="sectiontitle" id="custombehavior.11">Setter/getter key argument <a class="sectionlink" href="#custombehavior.11">§</a></h2><p>Ecmascript standard behavior is that setters and getters are not given
the name of the property being accessed.  This prevents reusing a single
setter or a getter for multiple properties; separate functions are needed
for each property which is sometimes inconvenient and wastes memory.</p><p>Duktape provides the property key name as a non-standard additional
argument to setter and getter functions.  See
<a href="https://github.com/svaarala/duktape/blob/master/tests/ecmascript/test-dev-nonstd-setget-key-argument.js">test-dev-nonstd-setget-key-argument.js</a>
and <a href="#propertyvirtualization">Property virtualization</a>
for more discussion.  The strict standards compliant behavior can be enabled
by disabling the config options <code>DUK_USE_NONSTD_GETTER_KEY_ARGUMENT</code>
and <code>DUK_USE_NONSTD_SETTER_KEY_ARGUMENT</code>.</p><h2 class="sectiontitle" id="custombehavior.12">Object.setPrototypeOf and Object.prototype.__proto__ (ES2015) <a class="sectionlink" href="#custombehavior.12">§</a></h2><p>See <a href="#es6-proto">Object.setPrototypeOf and Object.prototype.__proto__</a>.</p><h2 class="sectiontitle" id="custombehavior.13">Proxy object (ES2015) <a class="sectionlink" href="#custombehavior.13">§</a></h2><p>See <a href="#es6-proxy">Proxy object (subset)</a>.</p><h2 class="sectiontitle" id="custombehavior.14">JSON.stringify() escapes U+2028 and U+2029 <a class="sectionlink" href="#custombehavior.14">§</a></h2><p><code>JSON.stringify()</code> standard behavior is to output U+2028 and
U+2029 without escaping.  This leads to counterintuitive behavior when the
output is used in a web page or parsed with <code>eval()</code>: the U+2028
and U+2029 characters are considered line terminators which leads to a syntax
error (unterminated string).  Duktape escapes U+2028 and U+2029 by default
to avoid this issue; you can turn on the compliant behavior by disabling the
config option <code>DUK_USE_NONSTD_JSON_ESC_U2028_U2029</code>.</p><h2 class="sectiontitle" id="custombehavior.15">String.fromCharCode() accepts 32-bit codepoints <a class="sectionlink" href="#custombehavior.15">§</a></h2><p><code>String.fromCharCode()</code> standard behavior is to use ToUInt16()
coercion for codepoint values.  Duktape uses ToUint32() by default to better
support non-BMP strings.  You can force the compliant behavior by disabling
the config optipn <code>DUK_USE_NONSTD_STRING_FROMCHARCODE_32BIT</code>.</p><h2 class="sectiontitle" id="custombehavior.16">Array instance numeric index writes <a class="sectionlink" href="#custombehavior.16">§</a></h2><p>By default Duktape provides a fast path for writing to Array instances.
The fast path is active when numeric indices are used (e.g. <code>arr[7] = 'foo'</code>)
and a few internal conditions are met.  When the fast path is taken, Duktape
doesn't check Array.prototype for conflicting properties (these are very rare in
practical code), which makes common array writes faster.  The behavior is
non-compliant, but there's no outward difference unless Array.prototype has
properties with numeric keys.  You can turn on the compliant behavior by
disaling the config options <code>DUK_USE_NONSTD_ARRAY_WRITE</code> and
<code>DUK_USE_ARRAY_PROP_FASTPATH</code>.  See the following for more
details on the fast path behavior:
<a href="https://github.com/svaarala/duktape/blob/master/tests/ecmascript/test-misc-array-fast-write.js">test-misc-array-fast-write.js</a>.</p><h2 class="sectiontitle" id="typedarray-custombehavior">TypedArray binding <a class="sectionlink" href="#typedarray-custombehavior">§</a></h2><p>Duktape provides the ES2015 TypedArray binding, with some details yet
to be fixed, e.g. small differences in argument coercion e.g. for offset
and length values.</p><p>The plain buffer custom type behaves mostly like an Uint8Array object
for Ecmascript code, but has a separate type in the Duktape C API.</p><h2 class="sectiontitle" id="nodejsbuffer-custombehavior">Node.js Buffer binding <a class="sectionlink" href="#nodejsbuffer-custombehavior">§</a></h2><p>Duktape provides a Node.js-like <code>Buffer</code> binding.  There are
some differences between the Node.js behavior and Duktape behavior.  These
differences include:</p><ul>
<li>Interoperability with other buffer types: ArrayBuffer, DataView, or a
    typed array (Uint8Array etc) is usually allowed wherever a Node.js Buffer
    would be allowed.</li>
<li>Buffer data is always zeroed on allocation and when concatenation
    <code>totalLength</code> exceeds combined size of input buffers.</li>
<li>Read/write offset and length arguments are always validated to ensure
    memory safe behavior, even when <code>noAssert</code> is true.  Failed
    reads return NaN and failed writes return 0.</li>
<li>Partial read/writes are never done: if a read/write is partially
    outside the valid buffer, it is rejected.</li>
<li>Small differences in argument coercion for e.g. offset and length
    values.</li>
<li>Write calls coerce their value argument like TypedArray, e.g. when
    writing 0x100 using <code>writeUInt8()</code> silently coerces to
    0x00 rather than throwing a TypeError.</li>
<li>Duktape only supports the <code>"utf8"</code> encoding (and accepts no
    spelling variants).  Most API calls ignore an encoding argument, and
    use UTF-8 implicitly for string-to-buffer coercion.</li>
<li>UTF-8 decoding replacement character approach follows
    <a href="http://unicode.org/review/pr-121.html">Unicode Technical Committee Recommended Practice for Replacement Characters</a>
    which matches WHATWG Encoding API specification but differs from Node.js
    (at least up to version v6.9.1).</li>
</ul><hr/><h1 class="sectiontitle" id="customjson">Custom JSON formats <a class="sectionlink" href="#customjson">§</a></h1><h2 class="sectiontitle" id="customjson.1">Ecmascript JSON shortcomings <a class="sectionlink" href="#customjson.1">§</a></h2><p>The standard JSON format has a number of shortcomings when used with
Ecmascript:</p><ul>
<li><code>undefined</code> and function values are not supported</li>
<li>NaN and infinity values are not supported</li>
<li>Duktape custom types are, of course, not supported</li>
<li>Codepoints above BMP cannot be represented except as surrogate pairs</li>
<li>Codepoints above U+10FFFF cannot be represented even as surrogate pairs</li>
<li>The output is not printable ASCII which is often inconvenient</li>
</ul><p>These limitations are part of the Ecmascript specification which
explicitly prohibits more lenient behavior.  Duktape provides two more
programmer friendly custom JSON format variants: <b>JX</b> and <b>JC</b>,
described below.</p><h2 class="sectiontitle" id="customjson.2">Custom JX format <a class="sectionlink" href="#customjson.2">§</a></h2><p>JX encodes all values in a very readable manner and parses back
almost all values in a faithful manner (function values being the most
important exception).  Output is pure printable ASCII, codepoints above
U+FFFF are encoded with a custom escape format, and quotes around object
keys are omitted in most cases.  JX is not JSON compatible but a very
readable format, most suitable for debugging, logging, etc.</p><p>JX is used as follows:</p><pre class="ecmascript-code"><span class="keyword">var</span><span class="normal"> obj </span><span class="symbol">=</span><span class="normal"> </span><span class="cbracket">{</span><span class="normal"> foo</span><span class="symbol">:</span><span class="normal"> </span><span class="number">0</span><span class="symbol">/</span><span class="number">0</span><span class="symbol">,</span><span class="normal"> bar</span><span class="symbol">:</span><span class="normal"> </span><span class="symbol">[</span><span class="normal"> </span><span class="number">1</span><span class="symbol">,</span><span class="normal"> undefined</span><span class="symbol">,</span><span class="normal"> </span><span class="number">3</span><span class="normal"> </span><span class="symbol">]</span><span class="normal"> </span><span class="cbracket">}</span><span class="symbol">;</span>
<span class="function">print</span><span class="symbol">(</span><span class="normal">Duktape</span><span class="symbol">.</span><span class="function">enc</span><span class="symbol">(</span><span class="string">'jx'</span><span class="symbol">,</span><span class="normal"> obj</span><span class="symbol">));</span>
<span class="comment">// prints out: {foo:NaN,bar:[1,undefined,3]}</span>

<span class="keyword">var</span><span class="normal"> dec </span><span class="symbol">=</span><span class="normal"> Duktape</span><span class="symbol">.</span><span class="function">dec</span><span class="symbol">(</span><span class="string">'jx'</span><span class="symbol">,</span><span class="normal"> </span><span class="string">'{ foo: 123, bar: undefined, quux: NaN }'</span><span class="symbol">);</span>
<span class="function">print</span><span class="symbol">(</span><span class="normal">dec</span><span class="symbol">.</span><span class="normal">foo</span><span class="symbol">,</span><span class="normal"> dec</span><span class="symbol">.</span><span class="normal">bar</span><span class="symbol">,</span><span class="normal"> dec</span><span class="symbol">.</span><span class="normal">quux</span><span class="symbol">);</span>
<span class="comment">// prints out: 123 undefined NaN</span>
</pre><h2 class="sectiontitle" id="customjson.3">Custom JC format <a class="sectionlink" href="#customjson.3">§</a></h2><p>JC encodes all values into standard JSON.  Values not supported by
standard JSON are encoded as objects with a marker key beginning with an
underscore (e.g. <code>{"_ptr":"0xdeadbeef"}</code>).  Such values parse
back as ordinary objects.  However, you can revive them manually more or
less reliably.  Output is pure printable ASCII; codepoints above U+FFFF
are encoded as plain string data with the format "U+nnnnnnnn"
(e.g. <code>U+0010fedc</code>).</p><p>JC is used as follows:</p><pre class="ecmascript-code"><span class="keyword">var</span><span class="normal"> obj </span><span class="symbol">=</span><span class="normal"> </span><span class="cbracket">{</span><span class="normal"> foo</span><span class="symbol">:</span><span class="normal"> </span><span class="number">0</span><span class="symbol">/</span><span class="number">0</span><span class="symbol">,</span><span class="normal"> bar</span><span class="symbol">:</span><span class="normal"> </span><span class="symbol">[</span><span class="normal"> </span><span class="number">1</span><span class="symbol">,</span><span class="normal"> undefined</span><span class="symbol">,</span><span class="normal"> </span><span class="number">3</span><span class="normal"> </span><span class="symbol">]</span><span class="normal"> </span><span class="cbracket">}</span><span class="symbol">;</span>
<span class="function">print</span><span class="symbol">(</span><span class="normal">Duktape</span><span class="symbol">.</span><span class="function">enc</span><span class="symbol">(</span><span class="string">'jc'</span><span class="symbol">,</span><span class="normal"> obj</span><span class="symbol">));</span>
<span class="comment">// prints out: {"foo":{"_nan":true},"bar":[1,{"_undef":true},3]}</span>

<span class="keyword">var</span><span class="normal"> dec </span><span class="symbol">=</span><span class="normal"> Duktape</span><span class="symbol">.</span><span class="function">dec</span><span class="symbol">(</span><span class="string">'jc'</span><span class="symbol">,</span><span class="normal"> </span><span class="string">'{ "foo": 123, "bar": {"_undef":true}, "quux": {"_nan":true} }'</span><span class="symbol">);</span>
<span class="function">print</span><span class="symbol">(</span><span class="normal">dec</span><span class="symbol">.</span><span class="normal">foo</span><span class="symbol">,</span><span class="normal"> dec</span><span class="symbol">.</span><span class="normal">bar</span><span class="symbol">,</span><span class="normal"> dec</span><span class="symbol">.</span><span class="normal">quux</span><span class="symbol">);</span>
<span class="comment">// prints out: 123 [object Object] [object Object]</span>
</pre><p>The JC decoder is essentially the same as the standard JSON decoder
at the moment: all JC outputs are valid JSON and no custom syntax is needed.
As shown in the example, custom values (like <code>{"_undef":true}</code>)
are <b>not</b> revived automatically.  They parse back as ordinary objects
instead.</p><h2 class="sectiontitle" id="customjson.4">Codepoints above U+FFFF and invalid UTF-8 data <a class="sectionlink" href="#customjson.4">§</a></h2><p>All standard Ecmascript strings are valid CESU-8 data internally, so
behavior for codepoints above U+FFFF never poses compliance issues.  However,
Duktape strings may contain <a href="#extended-utf8">extended UTF-8</a>
codepoints and may even contain invalid UTF-8 data.</p><p>The Duktape JSON implementation, including the standard Ecmascript JSON API,
use replacement characters to deal with invalid UTF-8 data.  The resulting
string may look a bit odd, but this behavior is preferable to throwing an
error.</p><h2 class="sectiontitle" id="customjson.5">JSON format examples <a class="sectionlink" href="#customjson.5">§</a></h2><p>The table below summarizes how different values encode in each
encoding:</p><table>
<thead>
<tr>
<th>Value</th>
<th>Standard JSON</th>
<th>JX</th>
<th>JC</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
<tr>
<td>undefined</td>
<td>n/a</td>
<td><code>undefined</code></td>
<td><code>{"_undef":true}</code></td>
<td>Standard JSON: encoded as <code>null</code> inside arrays, otherwise omitted</td>
</tr>
<tr>
<td>null</td>
<td><code>null</code></td>
<td><code>null</code></td>
<td><code>null</code></td>
<td>standard JSON</td>
</tr>
<tr>
<td>true</td>
<td><code>true</code></td>
<td><code>true</code></td>
<td><code>true</code></td>
<td>standard JSON</td>
</tr>
<tr>
<td>false</td>
<td><code>false</code></td>
<td><code>false</code></td>
<td><code>false</code></td>
<td>standard JSON</td>
</tr>
<tr>
<td>123.4</td>
<td><code>123.4</code></td>
<td><code>123.4</code></td>
<td><code>123.4</code></td>
<td>standard JSON</td>
</tr>
<tr>
<td>+0</td>
<td><code>0</code></td>
<td><code>0</code></td>
<td><code>0</code></td>
<td>standard JSON</td>
</tr>
<tr>
<td>-0</td>
<td><code>0</code></td>
<td><code>-0</code></td>
<td><code>-0</code></td>
<td>Standard JSON allows <code>-0</code> but serializes negative
    zero as <code>0</code> (losing the sign unnecessarily)</td>
</tr>
<tr>
<td>NaN</td>
<td><code>null</code></td>
<td><code>NaN</code></td>
<td><code>{"_nan":true}</code></td>
<td>Standard JSON: always encoded as <code>null</code></td>
<td></td>
</tr>
<tr>
<td>Infinity</td>
<td><code>null</code></td>
<td><code>Infinity</code></td>
<td><code>{"_inf":true}</code></td>
<td>Standard JSON: always encoded as <code>null</code></td>
</tr>
<tr>
<td>-Infinity</td>
<td><code>null</code></td>
<td><code>-Infinity</code></td>
<td><code>{"_ninf":true}</code></td>
<td>Standard JSON: always encoded as <code>null</code></td>
</tr>
<tr>
<td>"köhä"</td>
<td><code>"köhä"</code></td>
<td><code>"k\xf6h\xe4"</code></td>
<td><code>"k\u00f6h\u00e4"</code></td>
<td></td>
</tr>
<tr>
<td>U+00FC</td>
<td><code>"\u00fc"</code></td>
<td><code>"\xfc"</code></td>
<td><code>"\u00fc"</code></td>
<td></td>
</tr>
<tr>
<td>U+ABCD</td>
<td><code>"\uabcd"</code></td>
<td><code>"\uabcd"</code></td>
<td><code>"\uabcd"</code></td>
<td></td>
</tr>
<tr>
<td>U+1234ABCD</td>
<td><code>"U+1234abcd"</code></td>
<td><code>"\U1234abcd"</code></td>
<td><code>"U+1234abcd"</code></td>
<td>Non-BMP characters are not standard Ecmascript, JX format borrowed from Python</td>
</tr>
<tr>
<td>object</td>
<td><code>{"my_key":123}</code></td>
<td><code>{my_key:123}</code></td>
<td><code>{"my_key":123}</code></td>
<td>ASCII keys matching identifer requirements encoded without quotes in JX</td>
</tr>
<tr>
<td>array</td>
<td><code>["foo","bar"]</code></td>
<td><code>["foo","bar"]</code></td>
<td><code>["foo","bar"]</code></td>
<td></td>
</tr>
<tr>
<td>buffer</td>
<td><code>n/a</code></td>
<td><code>|deadbeef|</code></td>
<td><code>{"_buf":"deadbeef"}</code></td>
<td></td>
</tr>
<tr>
<td>pointer</td>
<td><code>n/a</code></td>
<td><code>(0xdeadbeef)<br/>(DEADBEEF)</code></td>
<td><code>{"_ptr":"0xdeadbeef"}<br/>{"_ptr":"DEADBEEF"}</code></td>
<td>Representation inside parentheses or quotes is platform specific</td>
</tr>
<tr>
<td>NULL pointer</td>
<td><code>n/a</code></td>
<td><code>(null)</code></td>
<td><code>{"_ptr":"null"}</code></td>
<td></td>
</tr>
<tr>
<td>function</td>
<td><code>n/a</code></td>
<td><code>{_func:true}</code></td>
<td><code>{"_func":true}</code></td>
<td>Standard JSON: encoded as <code>null</code> inside arrays, otherwise omitted</td>
</tr>
<tr>
<td>lightfunc</td>
<td><code>n/a</code></td>
<td><code>{_func:true}</code></td>
<td><code>{"_func":true}</code></td>
<td>Formats like ordinary functions</td>
</tr>
</tbody>
</table><h2 class="sectiontitle" id="customjson.6">Limitations <a class="sectionlink" href="#customjson.6">§</a></h2><p>Some limitations include:</p><ul>
<li>Only enumerable own properties are serialized in any of the formats.</li>
<li>Array properties (other than the entries) are not serialized.  This would
    be useful in e.g. logging, e.g. as <code>[1,2,3,"type":"point"]</code>.</li>
<li>There is no automatic revival of special values when parsing JC data.</li>
<li>There is no canonical encoding.  This would be easy to arrange with a simple
    option to sort object keys during encoding.</li>
</ul><p>(See internal documentation for more future work issues.)</p><hr/><h1 class="sectiontitle" id="customdirectives">Custom directives <a class="sectionlink" href="#customdirectives">§</a></h1><p>Ecmascript E5/E5.1 employs a
<a href="http://www.ecma-international.org/ecma-262/5.1/#sec-14.1">directive prologue</a>
to allow version or implementation specific features be activated.
The standard only provides one such directive, <code>"use strict"</code>, while
asm.js uses <code>"use asm"</code>.  Duktape custom directives are discussed
in this section.</p><h2 class="sectiontitle" id="use-duk-notail">use duk notail <a class="sectionlink" href="#use-duk-notail">§</a></h2><p>The <code>use duk notail</code> directive indicates that the function should
never be tail called.  Tail calls affect the call stack so they are visible in
stack traces (usually harmless) and affect functions which inspect the call stack
using e.g. <code>Duktape.act()</code>.  This directive may be useful in special
cases to ensure call stack has a known shape.  Example:</p><pre class="ecmascript-code"><span class="keyword">function</span><span class="normal"> </span><span class="function">noTailCall</span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="string">'use duk notail'</span><span class="symbol">;</span>

<span class="normal">    </span><span class="comment">// ...</span>
<span class="cbracket">}</span>
</pre><p>Native functions are never tailcalled, so a corresponding declaration is not
necessary for them.</p><hr/><h1 class="sectiontitle" id="bufferobjects">Buffer objects <a class="sectionlink" href="#bufferobjects">§</a></h1><h2 class="sectiontitle" id="bufferobjects.1">Overview of buffer types <a class="sectionlink" href="#bufferobjects.1">§</a></h2><p>Duktape provides the following buffer and buffer-related types:</p><table>
<tr>
<th>Type</th>
<th>Standard</th>
<th>Duktape version</th>
<th>Description</th>
</tr>
<tr>
<td>Plain buffer</td>
<td>No<br/>Duktape specific</td>
<td>1.0</td>
<td>Plain, primitive buffer value (not an object), similar to how a plain string relates to a String object.
    Behaves like an Uint8Array instance where possible, object coerces to an actual <code>Uint8Array</code>.</td>
</tr>
<tr>
<td>ArrayBuffer object</td>
<td>Yes<br/>ES2015</td>
<td>1.3</td>
<td>Standard object type for representing a byte array.  References an underlying plain buffer.</td>
</tr>
<tr>
<td>DataView, typed array objects</td>
<td>Yes<br/>ES2015</td>
<td>1.3</td>
<td>View objects to access an underlying ArrayBuffer.  References an underlying plain buffer.</td>
</tr>
<tr>
<td>Node.js Buffer object</td>
<td>No<br/>Node.js-like</td>
<td>1.3</td>
<td>Object with <a href="https://nodejs.org/api/buffer.html">Node.js Buffer API</a>,
    inherits from Uint8Array.prototype.  References an underlying plain buffer.</td>
</tr>
</table><p>See <a href="https://github.com/svaarala/duktape/blob/master/doc/buffers.rst">buffers.rst</a>
for a detailed discussion, including a
<a href="https://github.com/svaarala/duktape/blob/master/doc/buffers.rst#summary-of-buffer-related-values">detailed table of buffer types and their properties</a>.</p><h2 class="sectiontitle" id="bufferobjects.2">Plain buffers <a class="sectionlink" href="#bufferobjects.2">§</a></h2><p>Plain buffers are a non-standard memory efficient way of representing
buffer data.  Plain buffers mimic Uint8Array objects so that they inherit
from <code>Uint8Array.prototype</code>, are accepted as typed array
constructor arguments, and so on.  While plain buffers don't have a property
table and can't hold properties of their own, they have the following
virtual or inherited properties (example values are for a 24-byte buffer):</p><table>
<thead>
<tr>
<th>Property name</th>
<th>Example value</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>[index]</td>
<td>0-255</td>
<td>Index properties in the range [0, length-1].  Reads and writes behave
    like for <code>Uint8Array</code>.</td>
</tr>
<tr>
<td class="propname">length</td>
<td>24</td>
<td>Length of buffer in bytes.  Length is not writable, so you can't resize
    a buffer by assigning its length.</td>
</tr>
<tr>
<td class="propname">byteOffset</td>
<td>0</td>
<td>Always 0, present to match typed arrays.</td>
</tr>
<tr>
<td class="propname">byteLength</td>
<td>24</td>
<td>Same as <code>.length</code>.</td>
</tr>
<tr>
<td class="propname">BYTES_PER_ELEMENT</td>
<td>1</td>
<td>Always 1, present to match typed arrays.</td>
</tr>
<tr>
<td class="propname">buffer</td>
<td> </td>
<td>Getter property which returns a new ArrayBuffer instance backing to the
    plain buffer without making a copy.  Because plain buffers don't have a
    property table, a new ArrayBuffer is created on every property read.
    Absent if buffer object support is disabled in Duktape configuration.</td>
</tr>
</tbody>
</table><p>Buffer objects like ArrayBuffer and Node.js Buffer are implemented on top
of plain buffer values and provide additional functionality like view/slice
support, typed accessors, and methods to manipulate data in different endianness.
However, they have more overhead than plain buffers.</p><p>For more details, see:</p><ul>
<li><a href="http://wiki.duktape.org/HowtoBuffers.html">How to work with buffers</a></li>
<li><a href="#typealgorithms">Type algorithms</a></li>
<li><a href="https://github.com/svaarala/duktape/blob/master/doc/buffers.rst">buffers.rst</a></li>
</ul><h2 class="sectiontitle" id="bufferobjects.3">Working with buffers <a class="sectionlink" href="#bufferobjects.3">§</a></h2><p>Buffer values work in both C and Ecmascript code:</p><ul>
<li>For Ecmascript code most of the behavior is defined in the relevant API
    standards, with exceptions for Duktape-specific features like mixing
    different buffer types.</li>
<li>For C code there are API calls to work with
    <a href="api.html#taglist-buffer">plain buffers</a> and
    <a href="api.html#taglist-bufferobject">buffer objects</a>.</li>
</ul><p>See
<a href="http://wiki.duktape.org/HowtoBuffers.html">How to work with buffers</a>
for examples.</p><div class="note">
In special cases the plain buffer backing a buffer object may not be large
enough to cover the apparent size of the buffer object; the buffer object
is then "uncovered" or "unbacked".  Duktape guarantees memory safe behavior
for such buffers, but other than that behavior varies between calls.  For
example, a call may ignore the situation silently returning undefined, NaN,
or zero, or it may throw a TypeError.  <b>The behavior for unbacked buffers is
not part of versioning guarantees and may change between minor versions.</b>
</div><h2 class="sectiontitle" id="bufferobjects.4">Current limitations <a class="sectionlink" href="#bufferobjects.4">§</a></h2><ul>
<li>See <a href="#typedarray-custombehavior">TypedArray binding</a> custom
    behavior.</li>
<li>See <a href="#nodejsbuffer-custombehavior">Node.js Buffer binding</a> custom
    behavior.</li>
</ul><hr/><h1 class="sectiontitle" id="errorobjects">Error objects <a class="sectionlink" href="#errorobjects">§</a></h1><h2 class="sectiontitle" id="errorobjects.1">Property summary <a class="sectionlink" href="#errorobjects.1">§</a></h2><p>Ecmascript Error objects have very few standard properties, so many
Ecmascript implementations have added quite a few custom properties.
Duktape uses standard Error properties but also borrows the most useful
properties used by other implementations.  The number of "own" properties
of error objects is minimized to keep error objects as small as possible.</p><p>Error objects have the following properties (mostly inherited):</p><table>
<thead>
<tr><th>Property name</th><th>Compatibility</th><th>Description</th></tr>
</thead>
<tbody>
<tr><td class="propname">name</td><td>standard</td><td>Name of error, e.g. <code>TypeError</code>, inherited</td></tr>
<tr><td class="propname">message</td><td>standard</td><td>Optional message of error, own property, empty message inherited if absent</td></tr>
<tr><td class="propname">fileName</td><td>Rhino</td><td>Filename related to error source, inherited accessor</td></tr>
<tr><td class="propname">lineNumber</td><td>Rhino</td><td>Linenumber related to error source, inherited accessor</td></tr>
<tr><td class="propname">stack</td><td>V8</td><td>Traceback as a multi-line human redable string, inherited accessor</td></tr>
</tbody>
</table><div class="note">
Assigning the most useful <code>fileName</code> and <code>lineNumber</code> is
somewhat complicated.  The related issues and current behavior are described in:
<a href="https://github.com/svaarala/duktape/blob/master/doc/error-objects.rst">error-objects.rst</a>.
</div><p>If Duktape is compiled with traceback support:</p><ul>
<li><code>stack</code>, <code>fileName</code>, and <code>lineNumber</code> are
    accessor properties inherited from <code>Error.prototype</code>.  You can
    override the properties by simply assigning over them: an inherited setter
    will capture the write but will create an own property as if a normal
    assignment was done.  This behavior was changed in Duktape 1.4.0 to better
    match other engines.</li>
<li>The raw traceback data needed by the accessor properties is stored in an internal
    property (<code>\xFFTracedata</code>) which is not normally accessible from
    Ecmascript code.</li>
</ul><p>If Duktape is compiled without traceback support:</p><ul>
<li>The <code>stack</code> accessor will be equivalent to
    <code>Error.prototype.toString()</code>, so that printing the stacktrace
    always produces a useful, human readable result.</li>
<li><code>fileName</code> and <code>lineNumber</code> will be own properties
    of the Error object.  You can override the properties using assignment.</li>
</ul><p>When error objects are created using the Duktape API from C code and the
caller does not give a format string for a <code>message</code>, the <code>message</code>
property is set to a numeric error code given in the API call.  The type of
<code>message</code> will be number in this case; normally error messages are
strings.   In minimized Duktape builds all errors generated internally by
Duktape use numeric error codes only.</p><p>An object is considered an "error object" if its internal prototype
chain contains the (original) <code>Error.prototype</code> object.  Only
objects matching this criteria get augmented with e.g. traceback data.</p><h2 class="sectiontitle" id="errorobjects.2">Traceback <a class="sectionlink" href="#errorobjects.2">§</a></h2><p>The <code>stack</code> property is an accessor (setter/getter) property
which provides a printable traceback related to an error.  The traceback
reflects the call stack when the error object was created (not thrown).
Traceback data is automatically collected and added to an object:</p><ul>
<li>when an Error instance is constructed;</li>
<li>when an error is thrown from C code using the Duktape API;</li>
<li>when an error is thrown from inside Duktape.</li>
</ul><p>The data used to create the traceback is stored in an internal property
(<code>\xFFTracedata</code>), in an internal and version-dependent format
described
<a href="https://github.com/svaarala/duktape/blob/master/doc/error-objects.rst">error-objects.rst</a>.
You shouldn't access the traceback data directly.</p><p>The printable traceback format is intended to be human readable only.
You shouldn't rely on an exact traceback format as it may change between
versions (for example,
<a href="https://github.com/svaarala/duktape/pull/592">tracebacks were improved for the 1.5.0 release</a>).
As an example of the current traceback format, the program:</p><pre class="ecmascript-code"><span class="comment">// shortened from tests/ecmascript/test-dev-traceback-example.js</span>
<span class="keyword">try</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="function">decodeURIComponent</span><span class="symbol">(</span><span class="string">'%e1%a9%01'</span><span class="symbol">);</span><span class="normal">  </span><span class="comment">// invalid utf-8</span>
<span class="cbracket">}</span><span class="normal"> </span><span class="keyword">catch</span><span class="normal"> </span><span class="symbol">(</span><span class="normal">e</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="function">print</span><span class="symbol">(</span><span class="normal">e</span><span class="symbol">.</span><span class="normal">stack</span><span class="symbol">);</span>
<span class="cbracket">}</span>
</pre><p>would print something like:</p><pre>
URIError: invalid input
    at [anon] (duk_bi_global.c:343) internal
    at decodeURIComponent () native strict preventsyield
    at global (test.js:3) preventsyield
</pre><p>In builds where tracebacks are disabled, the <code>stack</code> accessor
will return the same value as calling <code>toString()</code> on the error
would.  This means you can always print <code>e.stack</code> and get a useful
output.</p><p>The most portable traceback printing approach is something like:</p><pre class="ecmascript-code"><span class="keyword">try</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="function">decodeURIComponent</span><span class="symbol">(</span><span class="string">'%e1%a9%01'</span><span class="symbol">);</span><span class="normal">  </span><span class="comment">// invalid utf-8</span>
<span class="cbracket">}</span><span class="normal"> </span><span class="keyword">catch</span><span class="normal"> </span><span class="symbol">(</span><span class="normal">e</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="comment">// Print stacktrace on at least Duktape and V8, or a standard error</span>
<span class="normal">    </span><span class="comment">// string otherwise.</span>
<span class="normal">    </span><span class="function">print</span><span class="symbol">(</span><span class="normal">e</span><span class="symbol">.</span><span class="normal">stack </span><span class="symbol">||</span><span class="normal"> e</span><span class="symbol">);</span>
<span class="cbracket">}</span>
</pre><p>Attempt to write to <code>stack</code> is silently ignored.  You can still
override the accessor by defining an own property of the same name explicitly
with <code>Object.defineProperty()</code>.  This behavior differs from V8 where
<code>stack</code> is an own property of the Error instance, and if you assign a
value to <code>stack</code>, the value reads back as assigned.</p><h2 class="sectiontitle" id="error-handlers">Error handlers (errCreate and errThrow) <a class="sectionlink" href="#error-handlers">§</a></h2><p>If <code>Duktape.errCreate</code> has been set, it is called right after
Duktape has added traceback information to an object, and can process the
error further or even replace the error value entirely.  The error handler
only gets called with <code>Error</code> instances, and its return value is
used as the final error value.  If the error handler throws an error, that
error replaces the original error.  The error handler is usually called only once
per error.  However, in corner cases related to constructors, the error handler
can be called multiple times for a single error value.</p><p>An error handler should avoid overwriting any properties already
present in an object, as that would be quite confusing for other code.
In general, an error handler should always avoid throwing an error, as that
error replaces the original error and would also be confusing.  As a specific
example, an error handler must not try to add a new property to a non-extensible
object, as that would cause a <code>TypeError</code>.</p><p>Below is an example error handler for adding a creation timestamp to
errors at their creation:</p><pre class="ecmascript-code"><span class="normal">Duktape</span><span class="symbol">.</span><span class="normal">errCreate </span><span class="symbol">=</span><span class="normal"> </span><span class="keyword">function</span><span class="normal"> </span><span class="symbol">(</span><span class="normal">e</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="keyword">if</span><span class="normal"> </span><span class="symbol">(!(</span><span class="normal">e </span><span class="keyword">instanceof</span><span class="normal"> Error</span><span class="symbol">))</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">        </span><span class="comment">// this check is not really needed because errCreate only gets</span>
<span class="normal">        </span><span class="comment">// called with Error instances</span>
<span class="normal">        </span><span class="keyword">return</span><span class="normal"> e</span><span class="symbol">;</span>
<span class="normal">    </span><span class="cbracket">}</span>
<span class="normal">    </span><span class="keyword">if</span><span class="normal"> </span><span class="symbol">(</span><span class="string">'created'</span><span class="normal"> </span><span class="keyword">in</span><span class="normal"> e</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">        </span><span class="comment">// already augmented or conflicting property present</span>
<span class="normal">        </span><span class="keyword">return</span><span class="normal"> e</span><span class="symbol">;</span>
<span class="normal">    </span><span class="cbracket">}</span>
<span class="normal">    </span><span class="keyword">if</span><span class="normal"> </span><span class="symbol">(!</span><span class="normal">Object</span><span class="symbol">.</span><span class="function">isExtensible</span><span class="symbol">(</span><span class="normal">e</span><span class="symbol">))</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">        </span><span class="comment">// object not extensible, don't try to add a new property</span>
<span class="normal">        </span><span class="keyword">return</span><span class="normal"> e</span><span class="symbol">;</span>
<span class="normal">    </span><span class="cbracket">}</span>
<span class="normal">    e</span><span class="symbol">.</span><span class="normal">created </span><span class="symbol">=</span><span class="normal"> </span><span class="keyword">new</span><span class="normal"> </span><span class="function">Date</span><span class="symbol">();</span>
<span class="normal">    </span><span class="keyword">return</span><span class="normal"> e</span><span class="symbol">;</span>
<span class="cbracket">}</span>
</pre><p>To remove the handler, delete the property (setting it to e.g. <code>null</code>
does not work and causes a <code>TypeError</code> when Duktape attempts to
call the <code>null</code> value):</p><pre class="ecmascript-code"><span class="comment">// Remove error handler for error creation</span>
<span class="keyword">delete</span><span class="normal"> Duktape</span><span class="symbol">.</span><span class="normal">errCreate</span><span class="symbol">;</span>
</pre><p>Similarly, if <code>Duktape.errThrow</code> has been set, it is called
right before an error is thrown, and can process or replace the error value.
Because Ecmascript allows any value type to be thrown, the error handler
may get called with arbitrary input values (not just <code>Error</code>
instances).  It may also be called more than once for the same value because
an error can be re-thrown multiple times.</p><p>For example, to add a throw timestamp (recording the first time the object
has been thrown) to errors:</p><pre class="ecmascript-code"><span class="normal">Duktape</span><span class="symbol">.</span><span class="normal">errThrow </span><span class="symbol">=</span><span class="normal"> </span><span class="keyword">function</span><span class="normal"> </span><span class="symbol">(</span><span class="normal">e</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="keyword">if</span><span class="normal"> </span><span class="symbol">(!(</span><span class="normal">e </span><span class="keyword">instanceof</span><span class="normal"> Error</span><span class="symbol">))</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">        </span><span class="comment">// refuse to touch anything but Error instances</span>
<span class="normal">        </span><span class="keyword">return</span><span class="normal"> e</span><span class="symbol">;</span>
<span class="normal">    </span><span class="cbracket">}</span>
<span class="normal">    </span><span class="keyword">if</span><span class="normal"> </span><span class="symbol">(</span><span class="string">'thrown'</span><span class="normal"> </span><span class="keyword">in</span><span class="normal"> e</span><span class="symbol">)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">        </span><span class="comment">// already augmented or conflicting property present</span>
<span class="normal">        </span><span class="keyword">return</span><span class="normal"> e</span><span class="symbol">;</span>
<span class="normal">    </span><span class="cbracket">}</span>
<span class="normal">    </span><span class="keyword">if</span><span class="normal"> </span><span class="symbol">(!</span><span class="normal">Object</span><span class="symbol">.</span><span class="function">isExtensible</span><span class="symbol">(</span><span class="normal">e</span><span class="symbol">))</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">        </span><span class="comment">// object not extensible, don't try to add a new property</span>
<span class="normal">        </span><span class="keyword">return</span><span class="normal"> e</span><span class="symbol">;</span>
<span class="normal">    </span><span class="cbracket">}</span>
<span class="normal">    e</span><span class="symbol">.</span><span class="normal">thrown </span><span class="symbol">=</span><span class="normal"> </span><span class="keyword">new</span><span class="normal"> </span><span class="function">Date</span><span class="symbol">();</span>
<span class="normal">    </span><span class="keyword">return</span><span class="normal"> e</span><span class="symbol">;</span>
<span class="cbracket">}</span>
</pre><p>Again, to remove the handler, delete the property:</p><pre class="ecmascript-code"><span class="comment">// Remove error handler for error throwing</span>
<span class="keyword">delete</span><span class="normal"> Duktape</span><span class="symbol">.</span><span class="normal">errThrow</span><span class="symbol">;</span>
</pre><h2 class="sectiontitle" id="errorobjects.4">Current limitations <a class="sectionlink" href="#errorobjects.4">§</a></h2><ul>
<li>There is no cause chain support.  Cause chains would be useful but there
    are no cause chains in Ecmascript, nor does there seem to be a de facto
    standard for them.</li>
<li>These is currently no way to access traceback elements programmatically.</li>
<li>If an error is created with a non-constructor function call to a custom
    error class (<code>MyError('msg')</code> instead of <code>new MyError('msg')</code>)
    it won't get augmented with custom fields such as traceback data.  When
    called as a constructor custom errors inheriting from <code>Error</code> get
    augmented normally.  Built-in standard errors (like <code>TypeError</code>)
    always get augmented, even when created with a non-constructor function call
    (the tracebacks look slightly different depending on how the error is
    created, though).</li>
</ul><hr/><h1 class="sectiontitle" id="functionobjects">Function objects <a class="sectionlink" href="#functionobjects">§</a></h1><h2 class="sectiontitle" id="ecmascript-function-properties">Ecmascript functions <a class="sectionlink" href="#ecmascript-function-properties">§</a></h2><p>Duktape Function objects add a few properties to standard Ecmascript
properties.  The table below summarizes properties assigned to newly
created function instances (properties can of course be added or removed
afterwards):</p><table>
<thead>
<tr><th>Property name</th><th>Compatibility</th><th>Description</th></tr>
</thead>
<tbody>
<tr><td class="propname">length</td><td>standard</td><td>Function (nominal) argument count (if relevant).  Present for all Function objects, including bound functions.</td></tr>
<tr><td class="propname">prototype</td><td>standard</td><td>Prototype used for new objects when called as a constructor.  Present for most constructable Function objects, not copied to bound functions.</td></tr>
<tr><td class="propname">caller</td><td>standard</td><td>Accessor which throws an error.  Present for strict functions and bound functions.  Not copied to bound functions.  (If <code>DUK_USE_NONSTD_FUNC_CALLER_PROPERTY</code> is given, non-strict functions will get a non-standard <code>caller</code> property.)</td></tr>
<tr><td class="propname">arguments</td><td>standard</td><td>Accessor which throws an error.  Present for strict functions and bound functions.  Not copied to bound functions.</td></tr>
<tr><td class="propname">name</td><td>Duktape</td><td>Function name, see below.  Bound function name is based on this property, with a <code>"bound "</code> prefix (standard ES2015 behavior).</td></tr>
<tr><td class="propname">fileName</td><td>Duktape</td><td>Filename or context where function was declared (same name as in error tracebacks).  Copied to bound function from target function. </td></tr>
<tr><td class="propname">callee</td><td>n/a</td><td>Never assigned by default (listed here to clarify relationship to "caller" property).</td></tr>
</tbody>
</table><p>The <code>name</code> property is assigned to all functions and is also
the name used in tracebacks.  It is assigned as follows:</p><pre class="ecmascript-code"><span class="keyword">function</span><span class="normal"> </span><span class="function">funcDecl</span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="comment">/* Function declaration: 'name' is declaration name, here 'funcDecl'. */</span>
<span class="cbracket">}</span>

<span class="keyword">var</span><span class="normal"> foo </span><span class="symbol">=</span><span class="normal"> </span><span class="keyword">function</span><span class="normal"> </span><span class="function">namedFunc</span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="comment">/* Named function expression: 'name' is the name used in expression,</span>
<span class="comment">     * here 'namedFunc' (not 'foo').</span>
<span class="comment">     */</span>
<span class="cbracket">}</span>

<span class="keyword">var</span><span class="normal"> bar </span><span class="symbol">=</span><span class="normal"> </span><span class="keyword">function</span><span class="normal"> </span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="comment">/* Anonymous function expression: 'name' is the empty string. */</span>
<span class="cbracket">}</span>
</pre><div class="note">
Several Ecmascript built-in functions have properties different from user
created Functions.
</div><h2 class="sectiontitle" id="duktapec-function-properties">Duktape/C functions <a class="sectionlink" href="#duktapec-function-properties">§</a></h2><p>User-created Duktape/C functions (<code>duk_push_c_function()</code>) have
a different set of properties to reduce Function object memory footprint:</p><table>
<thead>
<tr><th>Property name</th><th>Compatibility</th><th>Description</th></tr>
</thead>
<tbody>
<tr><td class="propname">length</td><td>standard</td><td>
Function argument count, matches argument to <code>duk_push_c_function()</code>, 0 for varargs.
Non-writable and non-configurable.</td></tr>
</tbody>
</table><p>Note in particular that the standard <code>prototype</code>, <code>caller</code>,
and <code>arguments</code> properties are missing by default.  This is not strictly
compliant but is important to reduce function footprint.  User code can of course
assign these properties but is not required to do so.</p><p>There's also no (non-standard) <code>name</code> property.  Setting it manually
is useful because it affects how a function appears in tracebacks.</p><h2 class="sectiontitle" id="duktapec-lightfunc-properties">Lightweight Duktape/C functions <a class="sectionlink" href="#duktapec-lightfunc-properties">§</a></h2><p>Lightweight Duktape/C functions (lightfuncs) are a very memory efficient way
of representing a native function in the Ecmascript environment.  Lightfuncs
don't have a property table so they can't hold properties.  However, they inherit
from <code>Function.prototype</code> and have the following virtual properties
(which are non-configurable and non-writable):</p><table>
<thead>
<tr><th>Property name</th><th>Compatibility</th><th>Description</th></tr>
</thead>
<tbody>
<tr><td class="propname">length</td><td>standard</td><td>Function (nominal) argument count.</td></tr>
<tr><td class="propname">name</td><td>Duktape</td><td>Function name: <code>"light_&lt;PTR&gt;_&lt;FLAGS&gt;"</code>.</td></tr>
</tbody>
</table><p>The <code>name</code> property is an automatically generated virtual
function name. &lt;PTR&gt; is a platform dependent dump of the Duktape/C
function pointer, and &lt;FLAGS&gt; is a raw hex dump of the 16-bit internal
control fields (the format is Duktape internal).  You shouldn't rely on a
specific format.  For example:</p><pre>
duk&gt; print(myLightFunc.name);
light_0805b94c_0511
</pre><p>As for ordinary functions, a lightfunc coerces to an implementation
dependent string.  You shouldn't rely on a specific format.  For example:</p><pre>
duk&gt; print(myLightFunc);
function light_0805b94c_0511() {"light"}
</pre><p>For more details, see:</p><ul>
<li><a href="http://wiki.duktape.org/HowtoLightfuncs.html">How to work with lightfuncs</a></li>
<li><a href="#typealgorithms">Type algorithms</a></li>
<li><a href="https://github.com/svaarala/duktape/blob/master/doc/lightweight-functions.rst">lightweight-functions.rst</a></li>
</ul><hr/><h1 class="sectiontitle" id="datetime">Date and time <a class="sectionlink" href="#datetime">§</a></h1><p>Date and time handling is often a portability issue when adapting Duktape
to more exotic environments.  The <code>duk_config.h</code> configuration
header selects platform specific providers needed to implement the
<code>Date</code> built-in.  Duktape has built-in providers for mainstream
platforms (Linux, Windows, OS X) which should usually work without changes.
You can also write an
<a href="https://github.com/svaarala/duktape/blob/master/doc/datetime.rst#external-date-providers">external Date provider</a>
for more exotic environments.  An external Date provider can also be used e.g.
when a time offset needs to be applied to the platform time, or when using
time virtualization.</p><p>Ecmascript code interacts with date/time through the standard
<code>Date</code> built-in which is, by specification, limited to millisecond
resolution.  There are currently no Duktape specific Ecmascript date/time APIs.
(A custom API may be added later to deal with sub-millisecond resolution.)</p><p>C code can of course use platform date/time APIs directly, but the Duktape
C API also provides date/time API calls.  These calls see the same time values
as Ecmascript code which may matter when e.g. time virtualization is used.
Using these calls makes your code platform neutral and thus more portable.
The Duktape C API allows sub-millisecond resolution for time values.  See
<a href="http://wiki.duktape.org/HowtoTimeValues.html">How to work with time values</a>
for more details.</p><hr/><h1 class="sectiontitle" id="random">Random numbers <a class="sectionlink" href="#random">§</a></h1><p>Random numbers are used internally for <code>Math.random()</code>.
They are also used currently for random pivot selection in the
<code>Array.prototype.sort()</code> implementation.</p><p>The default internal random number generator is
<a href="http://xoroshiro.di.unimi.it/xoroshiro128plus.c">xoroshiro128+</a> with
<a href="http://xorshift.di.unimi.it/splitmix64.c">SplitMix64</a> seed mixing.
<a href="http://www.woodmann.com/forum/archive/index.php/t-3100.html.">Shamir's three-op PRNG</a>
is used on low memory targets and when the compiler doesn't have 64-bit
types.  The generators are not suitable for serious statistics algorithms
due to e.g. limited quality of the seed material, and are not at all
suitable for cryptography.</p><p>You can replace the internal random number generator using the
<code>DUK_USE_GET_RANDOM_DOUBLE</code> config option.</p><hr/><h1 class="sectiontitle" id="debugger">Debugger <a class="sectionlink" href="#debugger">§</a></h1><p>Duktape has built-in debugger support as an option you can enable during
compilation.  Debugger support adds about 15-20kB of code footprint (depending
on what debugger features are enabled) and has very minimal memory footprint.
Debugger features include:</p><ul>
<li>Execution status information such running/paused at file/line, callstack,
    local variables for different callstack levels</li>
<li>Execution control including pause/resume, step over/into/out, breakpoints
    targeted at file/line, debugger statement</li>
<li>Generic Eval at any callstack level, get/put variable at any callstack
    level</li>
<li>A mechanism for application-defined requests (AppRequest) and notifications
    (AppNotify)</li>
<li>Heap object in-depth inspection, Duktape heap walking, and getting a
    full heap dump</li>
</ul><p>The debugger is based on the following main concepts:</p><ul>
<li>Duktape provides a built-in <b>debug protocol</b> which is the same for all
    applications.  The application doesn't need to parse or understand the
    debug protocol.  The debug protocol is a compact binary protocol so that
    it works well on low memory targets with low speed connectivity.  There
    is a <b>JSON mapping</b> for the debug protocol and a
<a href="https://github.com/svaarala/duktape/blob/master/debugger/duk_debug_proxy.js">JSON debug proxy</a>
    to make it easier to integrate a debug client.</li>
<li>The debug protocol runs over a reliable, stream-based <b>debug transport</b>.
    To maximize portability, the concrete transport is provided by application
    code as a set of callbacks implementing a stream interface.  A streamed
    transport allows unbuffered streaming of debug messages, which keeps memory
    usage very low.</li>
<li>A <b>debug client</b> terminates the transport connection and uses the Duktape
    debug protocol to interact with Duktape internals: pause/resume, stepping,
    breakpoints, eval, etc.  You can also use the JSON debug proxy for easier
    integration.</li>
<li>A very narrow <b>debug API</b> is used by the application code to attach and
    detach a debugger, and to provide the callbacks needed to implement the
    debug transport.  All other debug activity happens through the debug
    protocol which is implemented by Duktape directly with no application
    involvement.</li>
</ul><p>The most appropriate debug transport varies a lot between debug targets;
it can be Wi-Fi, Bluetooth, a serial line, a stream embedded into a custom
management protocol, etc.  Although there is no "standard" transport, a TCP
connection is a useful default.  The Duktape distributable includes all the
pieces you need to get started with debugging using a TCP transport:</p><ul>
<li>An example implementation of the callbacks needed for a TCP transport:
    <a href="https://github.com/svaarala/duktape/blob/master/examples/debug-trans-socket/">duk_trans_socket_unix.c</a>
    (there's also a Windows example)</li>
<li>Debugger support for the Duktape command line tool (<code>duk</code>) using
    the TCP transport: <code>--debugger</code> option</li>
<li>A debugger web UI based on
    <a href="http://nodejs.org/">Node.js</a>,
    <a href="http://expressjs.com/">Express</a>, and
    <a href="http://socket.io/">socket.io</a>:
    <a href="https://github.com/svaarala/duktape/blob/master/debugger/">duk_debug.js</a></li>
</ul><p>The Node.js based debugger web UI (<code>duk_debug.js</code>) can connect
to the Duktape command line, but can also talk directly with any other target
implementing a TCP transport.  You can also customize it to use a different
transport or use a proxy which converts between TCP and your custom transport.
It's also possible to write your own debug client from scratch and e.g.
integrate it to a custom IDE.  You can integrate directly with a debug target
using the binary debug protocol, or use the JSON proxy provided by
<a href="https://github.com/svaarala/duktape/blob/master/debugger/duk_debug.js">duk_debug.js</a>
(Node.js) or
<a href="https://github.com/svaarala/duktape/blob/master/debugger/duk_debug_proxy.js">duk_debug_proxy.js</a>
(DukLuv).</p><p>Debug targets and debug clients are intended to be mixed and matched:
apart from the transport (which is usually either TCP or easy to adapt) the
debug protocol is the same.  Core functionality will be the same regardless
of the debug client or the debug target, but some optional features may be
missing.  Debug clients and debug targets may also implement application
specific commands (AppRequest) and notifications (AppNotify) for richer
integration which can be used when both the client and the target support
them (they're easy and safe to ignore if not supported).  Custom commands
and notifications allow e.g. downloading of source files directly from the
target, deep inspection of the state of a custom memory allocator, rebooting
the target on command, etc.</p><p>For more details on the implementation and how to get started, see:</p><ul>
<li><a href="https://github.com/svaarala/duktape/blob/master/debugger/README.rst">debugger/README.rst</a></li>
<li><a href="https://github.com/svaarala/duktape/blob/master/doc/debugger.rst">debugger.rst</a></li>
<li><a href="https://github.com/svaarala/duktape/blob/master/examples/debug-trans-dvalue/">duk_trans_dvalue.c</a>:
    example debug transport with local debug protocol decoding/encoding</li>
<li><a href="https://github.com/svaarala/duktape/blob/master/debugger/duk_debug_proxy.js">duk_debug_proxy.js</a></li>
</ul><a name="writing-c-modules"></a><!-- for old links --><hr/><h1 class="sectiontitle" id="modules">Modules <a class="sectionlink" href="#modules">§</a></h1><h2 class="sectiontitle" id="modules.1">CommonJS module loading frameworks <a class="sectionlink" href="#modules.1">§</a></h2><p>There's no built-in module loading framework because it's difficult for a
single framework to match a wide variety of different module loading use cases.
The Duktape distributable includes several optional module loader frameworks,
for example:</p><table>
<tr>
<td><a href="https://github.com/svaarala/duktape/tree/master/extras/module-duktape">module-duktape</a></td>
<td>A Duktape 1.x compatible loader based on
<a href="http://wiki.commonjs.org/wiki/Modules/1.1.1">CommonJS modules version 1.1.1</a>,
with additional support for <code>module.exports</code> and a few Duktape specific
<code>module</code> object properties.  The internals are documented in
<a href="https://github.com/svaarala/duktape/blob/master/doc/modules.rst">modules.rst</a>,
see <a href="http://wiki.duktape.org/HowtoModules.html">How to use modules</a> for examples.
This loader was a built-in in Duktape 1.x but was moved into an optional extra in Duktape 2.x.</td>
</tr>
<tr>
<td><a href="https://github.com/svaarala/duktape/tree/master/extras/module-node">module-node</a></td>
<td>A <a href="https://nodejs.org/api/modules.html">Node.js modules</a> compatible
loader.  See <a href="http://wiki.duktape.org/HowtoNodejsModules.html">How to use Node.js-like modules</a>
for examples.</td>
</tr>
</table><p>You can also implement your own module loader from scratch: the above
loaders are implemented using the Duktape public API with no special access
to internals.</p><p>The module loaders provide a <code>require()</code> function which allows
modules to be loaded as follows:</p><pre class="ecmascript-code"><span class="keyword">var</span><span class="normal"> mod </span><span class="symbol">=</span><span class="normal"> </span><span class="function">require</span><span class="symbol">(</span><span class="string">'foo/bar'</span><span class="symbol">);</span>
<span class="normal">mod</span><span class="symbol">.</span><span class="function">hello</span><span class="symbol">();</span>
</pre><p>The loaders abstract actual module resolution/loading to user-provided hook(s)
to allow the loader to be embedded in wide variety of environments.  For example:</p><ul>
<li>Module loading can be used in environments with no file system by loading
modules from a set of virtual built-in files.</li>
<li>On-the-fly transpiling can be done during loading, for example using
<a href="https://babeljs.io/">Babel</a>.</li>
</ul><h2 class="sectiontitle" id="modules.2">ES2015 modules <a class="sectionlink" href="#modules.2">§</a></h2><p>There's currently no support for ES2015 import/export and ES2015 modules.</p><h2 class="sectiontitle" id="modules.3">C module convention <a class="sectionlink" href="#modules.3">§</a></h2><p>There's a recommended (but not mandatory) C module convention which allows
C modules to be loaded and initialized from DLLs:
<a href="https://github.com/svaarala/duktape/blob/master/doc/c-module-convention.rst">c-module-convention.rst</a>.</p><hr/><h1 class="sectiontitle" id="logging">Logging <a class="sectionlink" href="#logging">§</a></h1><p>The Duktape distributable includes a
<a href="https://github.com/svaarala/duktape/tree/master/extras/logging">logging framework</a>
with a small footprint, reasonable performance, and redirectable output.  The framework
was a built-in in Duktape 1.x but was moved into an optional extra in Duktape 2.x.</p><p>Basic usage example:</p><pre class="ecmascript-code"><span class="keyword">var</span><span class="normal"> val1 </span><span class="symbol">=</span><span class="normal"> </span><span class="string">'foo'</span><span class="symbol">;</span>
<span class="keyword">var</span><span class="normal"> val2 </span><span class="symbol">=</span><span class="normal"> </span><span class="number">123</span><span class="symbol">;</span>
<span class="keyword">var</span><span class="normal"> val3 </span><span class="symbol">=</span><span class="normal"> </span><span class="keyword">new</span><span class="normal"> </span><span class="function">Date</span><span class="symbol">(</span><span class="number">123456789e3</span><span class="symbol">);</span>

<span class="keyword">var</span><span class="normal"> logger </span><span class="symbol">=</span><span class="normal"> </span><span class="keyword">new</span><span class="normal"> Duktape</span><span class="symbol">.</span><span class="function">Logger</span><span class="symbol">();</span><span class="normal">  </span><span class="comment">// or new Duktape.Logger('logger name')</span>
<span class="normal">logger</span><span class="symbol">.</span><span class="function">info</span><span class="symbol">(</span><span class="string">'three values:'</span><span class="symbol">,</span><span class="normal"> val1</span><span class="symbol">,</span><span class="normal"> val2</span><span class="symbol">,</span><span class="normal"> val3</span><span class="symbol">);</span>
</pre><p>The example would print something like the following to <code>stderr</code>:</p><pre>
2014-10-17T19:26:42.141Z INF test.js: three values: foo 123 1973-11-29 23:33:09.000+02:00
</pre><p>See the Wiki article
<a href="http://wiki.duktape.org/HowtoLogging.html">How to use logging</a> and
<a href="https://github.com/svaarala/duktape/blob/master/doc/logging.rst">logging.rst</a>
for more details.</p><hr/><h1 class="sectiontitle" id="finalization">Finalization <a class="sectionlink" href="#finalization">§</a></h1><h2 class="sectiontitle" id="finalization.1">Overview <a class="sectionlink" href="#finalization.1">§</a></h2><p>Duktape supports object finalization as a custom feature.  A finalizer
is called when an object is about to be freed, so that application code
can e.g. free native resources associated with the object.  The finalizer
can be either an Ecmascript function or a Duktape/C function.  However,
Ecmascript finalizers may interact badly with script timeouts, see below.</p><p>See <a href="http://wiki.duktape.org/HowtoFinalization.html">How to use finalization</a>
for examples.</p><h2 class="sectiontitle" id="finalization.2">Getting and setting the current finalizer <a class="sectionlink" href="#finalization.2">§</a></h2><p>An object which has an internal <code>_Finalizer</code> property in its
prototype chain (or in the object itself) is subject to finalization before
being freed.  The internal property should not be accessed directly, but can
be read/written using the following:</p><ul>
<li><code>Duktape.fin(obj)</code> (Ecmascript) or
    <code>duk_get_finalizer()</code> (C)
    gets the current finalizer.</li>
<li><code>Duktape.fin(obj, fn)</code> (Ecmascript) or
    <code>duk_set_finalizer()</code> (C)
    sets the current finalizer.</li>
</ul><h2 class="sectiontitle" id="finalization.3">Finalizer function arguments and return value <a class="sectionlink" href="#finalization.3">§</a></h2><p>The finalizer function is called with two arguments:</p><ul>
<li>The object being finalized.</li>
<li>A boolean flag indicating if the object is being forcibly freed as part
    of heap destruction.  This argument was added in Duktape 1.4.0:
    <ul>
<li>If <code>false</code> (normal case), the finalizer may rescue the object
        by creating a live reference to the object before returning and the
        finalizer is guaranteed to be called again later (heap destruction at
        the latest).</li>
<li>If <code>true</code> (forced finalization in heap destruction), the
        object cannot be rescued and will be forcibly freed after the finalizer
        finishes.  Native resources should be freed without expecting any further
        calls into the finalizer.</li>
</ul>
</li>
</ul><p>The return value of a finalizer is ignored.  Any errors thrown by the
finalizer are also silently ignored.</p><h2 class="sectiontitle" id="finalization.4">Finalizer execution guarantees <a class="sectionlink" href="#finalization.4">§</a></h2><p>The main finalizer guarantees are:</p><ul>
<li>Finalizers are executed for unreachable objects detected by reference
    counting or mark-and-sweep.  The finalizer may not execute immediately,
    however, not even when reference counting detects that the object became
    unreachable.</li>
<li>Finalizers are also executed for all remaining objects, regardless of
    their reachability status, when a Duktape heap is destroyed.</li>
<li>A finalizer is called exactly once, at the latest when the heap is
    destroyed, unless the object is rescued by the finalizer by making
    it reachable again.  An object may be rescued an arbitrary number of
    times; the finalizer is called exactly once for each "rescue cycle".
    Even with this guarantee in place, it's best practice for a finalizer
    to be re-entrant and carefully avoid e.g. freeing a native resource
    multiple times if re-entered.</li>
<li>A finalizer is not executed for a Proxy object, but is executed for
    the plain target object.  This ensures that a finalizer isn't executed
    multiple times when Proxy objects are created.</li>
</ul><p>Together these guarantee that a finalizer gets executed at some point
before a heap is destroyed, which allows native resources (such as sockets
and files) to be freed reliably.  There are two exceptions to this guarantee,
see below for more discussion:</p><ul>
<li>Heap destruction finalizer sanity limit may cause a finalizer not to
    be executed.</li>
<li>When a script timeout is being propagated out of the current callstack,
    Ecmascript finalizers will immediately rethrow the script timeout error.
    Duktape/C finalizers will execute normally.</li>
</ul><p>When the Duktape heap is being destroyed there are a few limitations for
finalizer behavior:</p><ul>
<li>Finalizers are executed for all finalizable objects in the heap,
    including reachable objects.</li>
<li>Finalizers cannot rescue objects; the semantics for a "rescue" would be
    ambiguous.  The finalizer's second argument is <code>true</code> when
    called during heap destruction to indicate rescue is not possible.</li>
<li>A finalizer can create new finalizable objects and these objects will also
    be finalized.  For example, a finalizer may post a HTTP notification of
    an object destruction which may use native network resources with their
    own finalizers.  However, there's a sanity limit to this process to ensure
    runaway finalizers cannot prevent a heap from being destroyed.</li>
<li>The finalizer sanity algorithm is version specific, see
    <a href="http://wiki.duktape.org/HowtoFinalization.html">How to use finalization</a>.
    The algorithm allows the number of finalizable objects to grow initially,
    but it must decrease in a reasonable time or the finalization process is
    aborted, which may cause some native resource leaks.</li>
</ul><h2 class="sectiontitle" id="finalization.5">Other current limitations <a class="sectionlink" href="#finalization.5">§</a></h2><ul>
<li>When script execution timeout
(<code>DUK_USE_EXEC_TIMEOUT_CHECK</code>)
is used and a timeout occurs, it's possible for an Ecmascript finalizer to start
running but immediately fail due to a script timeout.  If this is a concrete
concern, use a Duktape/C native finalizer instead which will run normally even
when propagating a timeout.</li>
<li>The context (Duktape thread) executing the finalizer can currently be any
    coroutine in the heap.  This must be taken into account in sandboxing.</li>
<li>Finalizers cannot currently yield.</li>
</ul><hr/><h1 class="sectiontitle" id="coroutines">Coroutines <a class="sectionlink" href="#coroutines">§</a></h1><p>Duktape has a support for simple coroutines.  Execution is strictly nesting:
coroutine A resumes or initiates coroutine B, coroutine B runs until it yields
or finishes (either successfully or through an uncaught error), after which
coroutine A continues execution with the yield result.</p><p>Coroutines are created with <code>new Duktape.Thread()</code>, which gets as its
sole argument the initial function where the new coroutine begins execution on
its first resume.  The resume argument becomes the initial function's first (and
only) argument value.</p><p>A coroutine is resumed using <code>Duktape.Thread.resume()</code> which takes the
following arguments: the coroutine to resume, the resume value, and (optionally)
a flag indicating whether the resume value is an ordinary value or an error to
be injected into the target coroutine.  Injecting an error means that the resume
value will be "thrown" at the site of the target coroutine's last yield operation.
In other words, instead of returning with an ordinary value, the yield will
seemingly throw an error.</p><p>A coroutine yields its current execution using <code>Duktape.Thread.yield()</code>
which takes as its arguments: the value to yield, and (optionally) a flag indicating
whether the yield value is an ordinary value or an error to be thrown in the
context of the resuming coroutine.  In other words, an error value causes the
resume operation to seemingly throw an error instead of returning an ordinary
value.</p><p>If a coroutine exists successfully, i.e. the initial function finishes by
returning a value, it is handled similarly to a yield with the return value.
If a coroutine exists because of an uncaught error, it is handled similarly
to a yield with the error: the resume operation will rethrow that error in
the resuming coroutine's context.  In either case the coroutine which has
finished can no longer be resumed; attempt to do so will cause a TypeError.</p><p>There are currently strict limitations on when a yield is possible.
In short, a coroutine can only yield if its entire active call stack consists
of plain Ecmascript-to-Ecmascript calls.  The following prevent a yield if
they are present anywhere in the yielding coroutine's call stack:</p><ul>
<li>a Duktape/C function call</li>
<li>a constructor call</li>
<li>a getter/setter call</li>
<li>a proxy trap call</li>
<li>an <code>eval()</code> call</li>
<li><code>Function.prototype.call()</code> or <code>Function.prototype.apply()</code></li>
<li>a finalizer call</li>
</ul><p>See <a href="http://wiki.duktape.org/HowtoCoroutines.html">How to use coroutines</a>
for examples.</p><a name="propertyvirtualization"></a><!-- for old links --><a name="virtualization-accessors"></a><!-- for old links --><a name="virtualization-proxy-object"></a><!-- for old links --><hr/><h1 class="sectiontitle" id="virtualproperties">Virtual properties <a class="sectionlink" href="#virtualproperties">§</a></h1><p>Duktape provides two mechanisms for interacting with property accesses
programmatically:</p><ul>
<li>Accessor properties (setters and getters)</li>
<li>The <code>Proxy</code> object</li>
</ul><p>See <a href="http://wiki.duktape.org/HowtoVirtualProperties.html">How to use virtual properties</a>
for examples.</p><a name="internalproperties"></a><!-- legacy links --><hr/><h1 class="sectiontitle" id="symbols">Symbols <a class="sectionlink" href="#symbols">§</a></h1><p>Duktape supports ES2015 Symbols and also provides a Duktape specific
<b>hidden Symbol</b> variant similar to internal strings in Duktape 1.x.
Hidden Symbols differ from ES2015 Symbols in that they're hidden from
ordinary Ecmascript code: they can't be created from Ecmascript code,
won't be enumerated or JSON-serialized, and won't be returned even from
<code>Object.getOwnPropertyNames()</code>.  Properties with hidden Symbol
keys can only be accessed by a direct property read/write when holding a
reference to a hidden Symbol.</p><p>Duktape uses hidden Symbols for various implementation specific purposes,
such as storing an object's finalizer reference.  User code can also use hidden
Symbols for its own purposes, e.g. to store hidden state in objects.  User code
should never try to access Duktape's hidden Symbol keyed properties: the set of
such properties can change arbitrarily between versions.</p><p>Symbols of all kinds are represented internally using byte sequences which
are invalid UTF-8; see
<a href="https://github.com/svaarala/duktape/blob/master/doc/symbols.rst">symbols.rst</a>
for the current formats in use.  When C code pushes a string using e.g.
<code>duk_push_string()</code> and the byte sequence matches an internal
Symbol format, the string value is automatically interpreted as a Symbol.</p><div class="note">
Note that the internal UTF-8 byte sequences cannot be created from Ecmascript
code as a valid Ecmascript string.  For example, a hidden Symbol might be
represented using <code>\xFFxyz</code>, i.e. the byte sequence
<code>ff 78 79 7a</code>, while the Ecmascript string <code>"\u00ffxyz"</code>
would be represented as the CESU-8 bytes <code>c3 bf 78 79 7a</code> in memory.
</div><p>Creating a Symbol is straightforward from C code:</p><pre class="c-code"><span class="comment">/* Create a hidden Symbol which can then be used to read/write properties.</span>
<span class="comment"> * The Symbol can be passed on to Ecmascript code like any other string or</span>
<span class="comment"> * Symbol.  Terminating a string literal after a hex escape is safest to</span>
<span class="comment"> * avoid some ambiguous cases like "\xffab".</span>
<span class="comment"> */</span>
<span class="function">duk_push_string</span><span class="symbol">(</span><span class="normal">ctx</span><span class="symbol">,</span><span class="normal"> </span><span class="string">"</span><span class="specialchar">\x</span><span class="string">ff"</span><span class="normal"> </span><span class="string">"mySymbol"</span><span class="symbol">);</span>
</pre><p>For more discussion on C string hex escaping, see
<a href="https://github.com/svaarala/duktape/blob/master/misc/c_hex_esc.c">c_hex_esc.c</a>.</p><p>Hidden Symbols cannot be created from Ecmascript code using the default
built-ins alone.  Standard ES2015 Symbols can be created using the
<code>Symbol</code> built-in, e.g. as <code>Symbol.for('foo')</code>.
When sandboxing, ensure that application C bindings don't accidentally provide
a mechanism to create hidden Symbols by e.g. converting an input buffer as-is
to a string without applying an encoding.</p><p>There's currently no special access control for properties with hidden
Symbol keys: if user code has access to the Symbol, it can read/write the
property value.  This will most likely change in future major versions so
that Ecmascript code cannot access a property with a hidden Symbol key,
even when holding a reference to the hidden Symbol value.</p><hr/><h1 class="sectiontitle" id="bytecodedumpload">Bytecode dump/load <a class="sectionlink" href="#bytecodedumpload">§</a></h1><p>The API calls
<code><a href="api.html#duk_dump_function">duk_dump_function()</a></code> and
<code><a href="api.html#duk_load_function">duk_load_function()</a></code> allow
calling C code to (1) serialize an Ecmascript function into a portable
bytecode and then (2) load the bytecode to reconstitute the function.</p><p>The bytecode format is Duktape version specific and it's unsafe to
load bytecode from a different Duktape minor version (patch version
doesn't affect bytecode compatibility).  Duktape configuration options
may also affect bytecode compatibility, so dump/load source and target
must be compiled with the same options.  The bytecode format is platform
neutral so that you can compile bytecode on one platform and then load it
on another, which is useful for cross-platform builds.  Duktape does not
validate loaded bytecode so calling code must ensure bytecode is intact
and valid for the running Duktape version.</p><div class="note">
Calling code must ensure that bytecode being loaded is intact and valid
for the running Duktape version (i.e. it has been compiled with the same
version of Duktape and hasn't been modified since).  Loading invalid
bytecode may lead to memory unsafe behavior; loading maliciously crafted
bytecode may even lead to exploitable vulnerabilities.
</div><p>See
<a href="https://github.com/svaarala/duktape/blob/master/doc/bytecode.rst">bytecode.rst</a>
for more details.</p><hr/><h1 class="sectiontitle" id="threading">Threading <a class="sectionlink" href="#threading">§</a></h1><p>Duktape supports a limited form of multithreading:</p><ul>
<li>A particular Duktape heap created with <code>duk_create_heap()</code> is
    single threaded: only one native thread can execute code in the heap at a
    time.  The native thread can change over time, as long as two native threads
    are not active at the same time in the same Duktape heap.</li>
<li>It is possible to suspend Duktape execution in a Duktape/C call using
    <code><a href="api.html#duk_suspend">duk_suspend()</a></code> and later
    resume it with <code><a href="api.html#duk_resume">duk_resume()</a></code>.
    Between these calls another thread may call into the same Duktape heap.
    Application code must manage any locking necessary to ensure only one
    native thread calls into Duktape at a time.</li>
<li>Duktape heaps are completely isolated from each other.  Multiple native
    threads can execute code at the same time, as long as there is only one
    active native thread per Duktape heap.</li>
<li>The <code><a href="api.html#duk_suspend">duk_suspend()</a></code> and
    <code><a href="api.html#duk_resume">duk_resume()</a></code> API calls
    (introduced in Duktape 1.6.0) allow a native thread to suspend while
    another native thread executes calls into a Duktape heap.</li>
</ul><p>For some background, a Duktape heap is a single memory management region
regardless of how many Duktape threads exist in the heap (don't confuse native
threads and Duktape threads).  Because the Duktape threads in a heap can share
object references, multithreading support would need synchronization for garbage
collection and all object handling.  Synchronization would be a major
portability issue, so a practical approach is to limit a Duktape heap to be
single threaded.  Duktape heaps don't share anything so there are no threading
limitations between them as a general rule.  However, when some platform features
are not available (such as variadic preprocessor macros or re-entrant system calls)
there are some limitations.</p><p>See
<a href="https://github.com/svaarala/duktape/blob/master/doc/threading.rst">threading.rst</a>
and <a href="http://wiki.duktape.org/HowtoMultipleNativeThreads.html">How to use multiple native threads</a>
for a detailed discussion of threading limitations and best practices.</p><hr/><h1 class="sectiontitle" id="sandboxing">Sandboxing <a class="sectionlink" href="#sandboxing">§</a></h1><p>Sandboxed environments allow execution of untrusted code with two broad
goals in mind:</p><ul>
<li>Security: prevent untrusted code from doing unsafe operations such as
    accessing memory directly, causing segfaults, etc.</li>
<li>Availability: prevent untrusted code from hogging resources, e.g.
    consuming all available memory or entering an infinite loop.</li>
</ul><p>Duktape provides mechanisms to achieve these goals for untrusted Ecmascript
code.  All C code is expected to be trusted.
See
<a href="https://github.com/svaarala/duktape/blob/master/doc/sandboxing.rst">sandboxing.rst</a>
for a detailed discussion of how to implement sandboxing.</p><div class="note">
Sandboxing support in Duktape 2.0 is still a work in progress.
</div><a name="performance-overview"></a><!-- for old links --><a name="performance-characteristics"></a><!-- for old links --><a name="performance-json-stringify-fastpath"></a><!-- for old links --><hr/><h1 class="sectiontitle" id="performance">Performance <a class="sectionlink" href="#performance">§</a></h1><p>Duktape is an interpreted engine with currently no JIT support.  It uses
reference counting which makes memory usage tight at the cost of some execution
performance.  Overall Duktape performance should be similar to other interpreted
languages.</p><p>See <a href="http://wiki.duktape.org/Performance.html">How to optimize performance</a>
for discussion of Duktape performance characteristics and hints to optimize code
for performance.</p><hr/><h1 class="sectiontitle" id="memoryusage">Memory usage <a class="sectionlink" href="#memoryusage">§</a></h1><p>Duktape allocates memory on demand and doesn't require a pre-allocated heap.
When you create a heap on a 32-bit system, Duktape needs about 70kB for the
built-in Ecmascript objects.  With specific
<a href="#memory-constrained-options">low memory options</a> initial memory
usage is about 27kB.  This can be further reduced to about 3kB when moving
built-in objects and strings to ROM (read-only data section).  It's also
possible to move custom native bindings fully into ROM.</p><p>After heap creation additional memory is then allocated as needed for
executing application scripts.  Reference counting ensures there is very
little unused allocated memory, the only exception being objects which
participate in reference loops; these are collected eventually by mark-and-sweep.</p><p>The memory allocations needed by Duktape fall into two basic categories.
First, there are a lot of small allocations between roughly 16 to 128 bytes
which are needed for strings, buffers, objects, object property tables, etc.
Second, there are much fewer larger allocations needed for e.g. Ecmascript
function bytecode, large strings and buffers, value stacks, the global string
table, and the Duktape heap object.</p><p>For most systems memory usage or the memory allocation pattern is not an
issue.  On low memory environments, e.g. less than 1MB of system RAM, you may
want to use a custom allocator to optimize memory usage.  A pool-based
allocator deals well with the small allocation churn without fragmentation
issues.  The downside is that you need to tune the memory pool sizes to match
the concrete allocation patterns.  You may want to use a pool allocator or a
hybrid allocated if the platform allocation primitives perform poorly with
a lot of small allocations.</p><p>See <a href="#memory-constrained-options">low memory options</a> and
<a href="https://github.com/svaarala/duktape/blob/master/doc/low-memory.rst">low-memory.rst</a>
for more discussion on what low memory features exists and how to tune the
memory pools for low memory systems.</p><a name="installing-system-wide"></a><!-- for old links --><hr/><h1 class="sectiontitle" id="compiling">Compiling <a class="sectionlink" href="#compiling">§</a></h1><h2 class="sectiontitle" id="compiling.1">Overview <a class="sectionlink" href="#compiling.1">§</a></h2><p>There are two basic steps to compiling Duktape:</p><ul>
<li><b>Configuration</b>.  Use <code>tools/configure.py</code> to prepare
    Duktape source and header files for compilation.  The requested Duktape
    configuration is described using configure.py command line options,
    see <a href="http://wiki.duktape.org/Configuring.html">Configuring Duktape for build</a>.
    For example:
<pre>
$ python2 tools/configure.py --output-directory /tmp/output -DDUK_USE_FASTINT -UDUK_USE_ES6_PROXY
$ ls /tmp/output/
duk_config.h  duk_source_meta.json  duktape.c  duktape.h
</pre></li>
<li><b>Compilation</b>.  Ensure that the generated header files are in the compiler
    include search path, and include the generate source file(s) in your application
    build; there's no official Duktape build script or Makefile.
    For example:
<pre>
$ gcc -O2 -Wall -otest -I/tmp/output /tmp/output/duktape.c my_application.c -lm
</pre></li>
</ul><p>While Duktape is usually compiled together with your application, you can
also build it into a static or shared library.  Duktape can also be installed
as a system-wide library, see
<a href="https://github.com/svaarala/duktape/blob/master/doc/system-install.rst">system-install.rst</a>.</p><div class="note">
The <code>DUK_OPT_xxx</code> feature options are no longer supported in
Duktape 2.x.  All configuration information is embedded in <code>duk_config.h</code>
and/or autogenerated sources and headers.
</div><a name="timing-sensitive-options"></a><!-- for old links --><a name="memory-constrained-options"></a><!-- for old links --><a name="performance-sensitive-options"></a><!-- for old links --><h2 class="sectiontitle" id="compiling.2">Configuring <a class="sectionlink" href="#compiling.2">§</a></h2><h3 class="sectiontitle" id="compiling.2.1">Preconfigured sources and default configuration <a class="sectionlink" href="#compiling.2.1">§</a></h3><p>The Duktape distributable contains preconfigured sources and headers with
a few variants:</p><ul>
<li><code>src/</code>: a single source file version which consists of
    <code>duk_config.h</code>, <code>duktape.h</code>, and <code>duktape.c</code>.</li>
<li><code>src-noline/</code>: same as <code>src/</code> but with no <code>#line</code>
    directives in the combined source file; this matters in some environments,
    see <a href="https://github.com/svaarala/duktape/pull/363">https://github.com/svaarala/duktape/pull/363</a>.</li>
<li><code>src-separate/</code>: a separate source files version which consists
    of <code>duk_config.h</code>, <code>duktape.h</code>, and a set of separate
    source files.  The single source file version is preferred, but separate
    files work better with some toolchains.</li>
</ul><p>These preconfigured sources provide automatic platform, compiler, and
architecture detection and use the Duktape default configuration:</p><ul>
<li>Full Ecmascript E5/E5.1 compliance
    (including the optional
    <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-B">Annex B</a>
    features), except for intentional real world compatibility deviations
    (see <a href="#custombehavior">Custom behavior</a>)</li>
<li>ES2015 typed array and Node.js Buffer support</li>
<li>Some features from <a href="#es6features">Ecmascript 2015 (E6)</a> and
    <a href="#es7features">Ecmascript 2016 (E7)</a></li>
<li>Packed value representation (8 bytes per value) when available,
    unpacked value representation (usually 16 bytes per value) when not</li>
<li>Reference counting and mark-and-sweep garbage collection</li>
<li>Full error messages and tracebacks</li>
<li>No debug printing, no asserts, etc</li>
<li>All portable fast paths enabled</li>
</ul><div class="note">
The preconfigured sources cannot be used to build Duktape into a Windows DLL.
Run <code>configure.py</code> with the <code>--dll</code> option to do that.
</div><h3 class="sectiontitle" id="compiling.2.2">Running configure.py to customize Duktape configuration <a class="sectionlink" href="#compiling.2.2">§</a></h3><p>The <code>configure.py</code> utility prepares Duktape source and header
files for a specific configuration described using command line options.
For example, to prepare Duktape sources for a DLL build with fastint
support enabled and Ecmascript 6 <code>Proxy</code> object support disabled:</p><pre>
# Default output format is single source file (--separate-sources for separate
# sources) and no #line directives (--line-directives to enable them).

$ python2 tools/configure.py \
      --output-directory /tmp/output \
      --dll \
      -DDUK_USE_FASTINT \
      -UDUK_USE_ES6_PROXY

# The output directory /tmp/output contains the header and source files to
# be included in your build.

$ ls /tmp/output
duk_config.h  duk_source_meta.json  duktape.c  duktape.h
</pre><p>Configuration options given to <code>configure.py</code> affect several
different aspects of the prepared header and source files, for example:</p><ul>
<li>Optional features in Duktape source code are enabled/disabled using config
    options (<code>DUK_USE_xxx</code>) which are provided by the
    <code>duk_config.h</code> configuration header.  The configuration
    header also handles platform, architecture, and compiler detection, and
    all other aspects of platform portability.</li>
<li>Built-in objects and strings are read in from metadata files and bit-packed
    built-in initialization data is generated.  It's also possible to supply
    custom metadata files to add custom built-in bindings or modify standard
    built-ins such as <code>Math</code> and <code>JSON</code>.</li>
<li>When using "ROM built-ins", built-in objects and strings are placed into the
    read-only code section to reduce RAM footprint.  The necessary source code
    for built-in object/string initializers is autogenerated by configure.py.
    Also custom built-ins can be placed in the read-only code section.</li>
<li>Unicode data files (UnicodeData.txt and SpecialCasing.txt) are converted into
    bit-packed run-time Unicode tables.  The Unicode data files can also be
    overridden e.g. to reduce Unicode table footprint.</li>
</ul><p>The <code>configure.py</code> utility requires Python 2.x support.  If your
build environment doesn't support Python 2.x, you can run <code>configure.py</code>
on a different platform and compile the resulting files in your build environment.</p><p>Even if the default options are OK, it's recommended that you run
<code>configure.py</code> as part of your build instead of using the
preconfigured sources. Custom options may be necessary on e.g. low memory
platforms.  See
<a href="http://wiki.duktape.org/Configuring.html">Configuring Duktape for build</a>
for more practical details.</p><a name="duktape-date-provider"></a><!-- for old links --><h3 class="sectiontitle" id="compiling.2.3">Commonly needed configuration options <a class="sectionlink" href="#compiling.2.3">§</a></h3><p>Some commonly needed configuration options are:</p><ul>
<li><b>DUK_USE_FATAL_HANDLER, strongly recommended</b>.  The built-in default fatal
    error handler will write a debug log message (but <b>won't</b> write anything to
    <code>stdout</code> to <code>stderr</code>), and will then call <code>abort()</code>.
    If that fails, it enters an infinite loop to ensure execution doesn't resume
    after a fatal error. This is usually not the best behavior for production
    applications which may already have better fatal error recovery mechanisms.
    To replace the default fatal handler, see
    <a href="http://wiki.duktape.org/HowtoFatalErrors.html">How to handle fatal errors</a>.</li>
<li><b>Long control transfer: setjmp/longjmp and C++ exceptions</b>.
    By default Duktape uses <code>setjmp()</code> and <code>longjmp()</code>
    (or their variants) for internal long control transfers.  If you're
    compiling with a C++ compiler you may want to use
    <code>DUK_USE_CPP_EXCEPTIONS</code> which causes Duktape to use C++
    exceptions for long control transfers and allows scope-based resource
    management (automatic destructors, etc; sometimes referred to as
    <a href="https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization">RAII</a>)
    in Duktape/C functions to work as expected.</li>
<li><b>Windows DLL build</b>.  Windows DLL build requires some
    <code>declspec()</code> declarations for DLL library symbols.  Use the
    <code>--dll</code> option when running <code>configure.py</code> to
    enable them for Duktape symbols.</li>
<li><b>Forced byte order or alignment</b>.  If you're using Duktape on a
    platform where Duktape's automatic feature detection doesn't (yet) work,
    you may need to force a specific byte order or alignment requirements
    during the configuration step.</li>
<li><b>Date built-in on exotic platforms</b>.  When porting to new or exotic
    platforms the Duktape built-in Date support may not work on the platform.
    In such a case you can implement an external "Date provider" which allows
    you to provide the necessary date/time primitives without Duktape changes.  See
    <a href="https://github.com/svaarala/duktape/blob/master/doc/datetime.rst">datetime.rst</a>.</li>
</ul><!-- XXX: this might be more suited to the Wiki --><h3 class="sectiontitle" id="compiling.2.4">Memory management alternatives <a class="sectionlink" href="#compiling.2.4">§</a></h3><p>There are two supported memory management alternatives:</p><ul>
<li><b>Reference counting and mark-and-sweep (default)</b>: heap objects are
    freed immediately when they become unreachable except for objects
    participating in unreachable reference cycles.  Such objects are freed by
    a periodic voluntary, stop the world mark-and-sweep collection.
    Mark-and-sweep is also used as the emergency garbage collector if
    memory allocation fails.</li>
<li><b>Mark-and-sweep only</b>: reduces code footprint and memory footprint
    (heap headers don't need to store a reference count), but there is more
    memory usage variance than in the default case.  The frequency of voluntary,
    stop the world mark-and-sweep collections is also higher than in the default
    case where reference counting is expected to handle almost all memory
    management.  Voluntary (non-emergency) mark-and-sweep can be disabled via
    config options.</li>
</ul><p>Reference counting relies on mark-and-sweep to handle reference cycles.
For example, every Ecmascript function instance is required to be in a
reference loop with an automatic prototype object created for the function.
You can break this loop manually if you wish.  For internal technical reasons,
named function expressions are also in a reference loop; this loop cannot be
broken from user code and only mark-and-sweep can collect such functions.</p><h2 class="sectiontitle" id="compiling.3">Compiling <a class="sectionlink" href="#compiling.3">§</a></h2><h3 class="sectiontitle" id="compiling.3.1">General guidelines <a class="sectionlink" href="#compiling.3.1">§</a></h3><p>Duktape doesn't have an official Makefile or a build script: given the
number of different portability targets, maintaining an official build
script would be difficult.  Instead, you should add Duktape to your existing
build process in whatever way is most natural.</p><p>Duktape is compiled with a C or C++ compiler (C99 is recommended)
and then linked to your program in some way; the exact details vary between
platforms and toolchains.  For example, you can:</p><ul>
<li>Compile Duktape together with your program without an explicit linking
    step.</li>
<li>Compile Duktape as a static library, and link the static library with
    your program.</li>
<li>Compile Duktape as a dynamic library, and link the dynamic library with
    your program.</li>
<li>Compile Duktape as a dynamic library, install it system-wide, and use it
    from several applications; see
    <a href="https://github.com/svaarala/duktape/blob/master/doc/system-install.rst">system-install.rst</a>.</li>
</ul><p>All Duktape API functions are potentially macros, and the implementation
of a certain API primitive may change between a macro and an actual function
even between compatible releases.  Some Duktape configuration options also
affect binary compatibility.  To ensure binary compatibility:</p><ul>
<li><b>Include <code>duktape.h</code> in application code</b>.  This is
    good practice in general, but without the header your compiler will
    incorrectly assume that all Duktape API functions are actual functions
    which will cause linking to fail.</li>
<li><b>Use the same prepared Duktape sources and headers when compiling
    Duktape and your application</b>.  This ensures Duktape and your application
    are compiled with the exactly same Duktape version and configuration.
    This is especially important when Duktape is compiled as a library in a
    separate compilation step.</li>
<li><b>Use the same compiler when compiling Duktape and your application</b>.
    Using a different compiler may affect e.g. type detection in the Duktape
    <code>duk_config.h</code> header or function calling convention, and thus
    compromise binary compatibility.  In practice compilers can be mixed to
    some extent, e.g. GCC and Clang are generally compatible.</li>
</ul><h3 class="sectiontitle" id="compiling.3.2">Recommended compiler options <a class="sectionlink" href="#compiling.3.2">§</a></h3><p>Recommended compiler options for GCC/clang, use similar options for
your compiler:</p><ul>
<li><code>-std=c99</code>: recommended to ensure C99 semantics
    which improve C type detection and allows Duktape to use variadic
    macros.</li>
<li><code>-Wall</code>: recommended to catch potential issues early.</li>
<li><code>-Os</code>: optimize for smallest footprint, which is usually
    desired when embedding Duktape.  <code>-O2</code> is a good compromise
    for performance optimized builds.</li>
<li><code>-fomit-frame-pointer</code>: omit frame pointer, further reduces
    footprint but may interfere with debugging (leave out from debug builds).</li>
<li><code>-fstrict-aliasing</code>: use strict aliasing rules, Duktape
    is compatible with these and they improve the resulting C code.</li>
<li>Configure.py with <code>--dll</code> is needed when Duktape is built as
    a DLL, at least when compiling for Windows.</li>
</ul><h3 class="sectiontitle" id="compiling.3.3">Compilation warnings <a class="sectionlink" href="#compiling.3.3">§</a></h3><p>Duktape usually compiles without warnings when using a mainstream compiler
(e.g. GCC, Clang, MSVC, or MinGW) in C99 mode with warnings enabled (e.g.
<code>-Wall</code> in gcc/clang), and using default Duktape configuration
options.  There may be some warnings when using a non-mainstream compiler,
very strict warning levels (like <code>-Wextra</code> in gcc/clang or
<code>/W4</code> in MSVC), or non-default Duktape configuration options.
Eliminating compilation warnings for all compilers and all configuration
option combinations is very difficult and is thus explicitly not a project
goal.  You're still encouraged to report warnings so that they can be fixed
if possible.</p><h3 class="sectiontitle" id="duktape-cplusplus">Using a C++ compiler <a class="sectionlink" href="#duktape-cplusplus">§</a></h3><p>Duktape works with both C and C++ compilers and applications.  You can
compile Duktape and the application with a C or a C++ compiler in any
combination.  Even so, it is recommended to compile both Duktape and the
application with the same compiler (i.e. both with a C compiler or both
with a C++ compiler) and with the same compiler options.</p><p>The <code>duktape.h</code> header contains the necessary glue to make all
of these combinations work.  Specifically, all symbols needed by Duktape
public API are inside a <code>extern "C" { ... }</code> wrapper when compiled
with a C++ compiler.  This ensures that such symbols are defined and used
without C++ name mangling.  Specifically:</p><ul>
<li>When compiling Duktape itself with a C++ compiler, symbols needed by
    Duktape public API are not mangled.  Other Duktape internal symbols will
    be mangled, but are not externally visible and should thus cause no
    problems even if the application is compiled with a C compiler.</li>
<li>When compiling an application with a C++ compiler, the wrapper ensures
    that Duktape public API symbols used by the application are looked up
    without mangling.</li>
</ul><p>If you mix C and C++ compilation, you should do the final linking with the
C++ toolchain.  At least when mixing gcc/g++ you may encounter something like:</p><pre>
$ g++ -c -o duktape.o -Isrc/ src/duktape.c
$ gcc -c -o duk_cmdline.o -Isrc/ examples/cmdline/duk_cmdline.c
$ gcc -o duk duktape.o duk_cmdline.o -lm
duktape.o:(.eh_frame+0x1ab): undefined reference to `__gxx_personality_v0'
collect2: error: ld returned 1 exit status
</pre><p>One fix is to use <code>g++</code> for linking:</p><pre>
$ g++ -c -o duktape.o -Isrc/ src/duktape.c
$ gcc -c -o duk_cmdline.o -Isrc/ examples/cmdline/duk_cmdline.c
$ g++ -o duk duktape.o duk_cmdline.o -lm
</pre><p>Because <code>duk_config.h</code> selects C/C++ data types needed by
Duktape and also does other feature detection, mixing C and C++ compilers
could theoretically cause the C and C++ compilers to end up with different
active features or data types.  If that were to happen, Duktape and the
application would be binary incompatible which would lead to very difficult
to diagnose issues.  This is usually not an issue, but to avoid the potential,
compile Duktape and the application with the same compiler.</p><p>By default scope-based resource management (sometimes referred to as
<a href="https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization">RAII</a>)
won't work in Duktape/C functions because Duktape uses
<code>longjmp()</code> for internal long control transfers, bypassing
C++ stack unwind mechanisms.  You can use <code>DUK_USE_CPP_EXCEPTIONS</code>
to cause Duktape to use C++ exceptions for internal long control transfers,
which allows scope-based resource management to work in Duktape/C functions.</p><hr/><h1 class="sectiontitle" id="portability">Portability <a class="sectionlink" href="#portability">§</a></h1><p>Duktape is widely portable to platforms with at least a C89 compiler.
Because Duktape has very limited dependency on platform functions, it's
possible to Duktape to very exotic platforms.  One major platform dependency
is the Date built-in which may need a custom provider for an exotic platform.</p><p>See <a href="http://wiki.duktape.org/Portability.html">Portability</a> for
platform and compiler specific portability issues, porting recommendations,
and troubleshooting tips.</p><hr/><h1 class="sectiontitle" id="compatibility">Compatibility <a class="sectionlink" href="#compatibility">§</a></h1><p>This section discussed Duktape compatibility with Ecmascript dialects,
extensions, frameworks, and test suites.</p><h2 class="sectiontitle" id="compatibility-e5">Ecmascript E5 / E5.1 <a class="sectionlink" href="#compatibility-e5">§</a></h2><p>The main compatibility goal of Duktape is to be Ecmascript E5/E5.1
compatible.  However, ES5 feature semantics are updated to ES2015 (or
later) where incompatible changes have been made in newer specification
versions.  Current level of compatibility should be quite high.</p><h2 class="sectiontitle" id="compatibility-e6">Ecmascript 2015 (E6) <a class="sectionlink" href="#compatibility-e6">§</a></h2><p>Duktape implements some features from Ecmascript 2015 (E6), but generally there
is no compatibility with E6 yet.</p><h2 class="sectiontitle" id="compatibility-e7">Ecmascript 2016 (E7) <a class="sectionlink" href="#compatibility-e7">§</a></h2><p>Duktape implements some features from Ecmascript 2016 (E7), but generally there
is no compatibility with E7 yet.</p><h2 class="sectiontitle" id="compatibility-e3">Ecmascript E3 <a class="sectionlink" href="#compatibility-e3">§</a></h2><p>There is no effort to maintain
<a href="http://www.mozilla.org/js/language/E262-3.pdf">Ecmascript E3</a>
compatibility, other than required by the E5/E5.1 specification.</p><h2 class="sectiontitle" id="compatibility-coffeescript">CoffeeScript <a class="sectionlink" href="#compatibility-coffeescript">§</a></h2><p><a href="http://coffeescript.org/">CoffeeScript</a> compiles to
JavaScript which should be compatible with Duktape.  There are no known
compatibility issues.</p><p>Some CoffeeScript examples are included in the distributable.  Simply
run <code>make</code> in <code>examples/coffee/</code>.  For instance,
<code>hello.coffee</code>:</p><pre class="coffeescript-code">
print 'Hello world!'
print 'version: ' + Duktape.version
</pre><p>compiles to:</p><pre class="ecmascript-code"><span class="symbol">(</span><span class="keyword">function</span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span>

<span class="normal">  </span><span class="function">print</span><span class="symbol">(</span><span class="string">'Hello world!'</span><span class="symbol">);</span>

<span class="normal">  </span><span class="function">print</span><span class="symbol">(</span><span class="string">'version: '</span><span class="normal"> </span><span class="symbol">+</span><span class="normal"> Duktape</span><span class="symbol">.</span><span class="normal">version</span><span class="symbol">);</span>

<span class="cbracket">}</span><span class="symbol">).</span><span class="function">call</span><span class="symbol">(</span><span class="keyword">this</span><span class="symbol">);</span>
</pre><h2 class="sectiontitle" id="compatibility-coco">Coco <a class="sectionlink" href="#compatibility-coco">§</a></h2><p>Like CoffeeScript, <a href="https://github.com/satyr/coco">Coco</a> compiles to
Javascript.  There are no known issues.</p><h2 class="sectiontitle" id="compatibility-livescript">LiveScript <a class="sectionlink" href="#compatibility-livescript">§</a></h2><p>Like CoffeeScript, <a href="http://livescript.net/">LiveScript</a> compiles to
Javascript.  There are no known issues.</p><h2 class="sectiontitle" id="compatibility-typescript">TypeScript <a class="sectionlink" href="#compatibility-typescript">§</a></h2><p><a href="https://github.com/Microsoft/TypeScript/">TypeScript</a>
compiles to Javascript.  There are no known issues with compiling TypeScript
using the Microsoft TypeScript compiler (in the ES5/CommonJS mode) and
running the resulting Javascript using Duktape.  It's also possible to
<a href="http://wiki.duktape.org/CompatibilityTypeScript.html">run the TypeScript compiler with Duktape</a>.</p><h2 class="sectiontitle" id="compatibility-underscorejs">Underscore.js <a class="sectionlink" href="#compatibility-underscorejs">§</a></h2><p><a href="http://underscorejs.org/">Underscore.js</a> provides a lot of
useful utilities to plain Ecmascript.  Duktape passes almost all of Underscore's
test cases, see
<a href="https://github.com/svaarala/duktape/blob/master/doc/underscore-status.rst">underscore-status.rst</a>
for current compatibility status.</p><h2 class="sectiontitle" id="compatibility-test262">Test262 <a class="sectionlink" href="#compatibility-test262">§</a></h2><p><a href="http://test262.ecmascript.org/">test262</a> is a test suite for
testing E5.1 compatibility, although it includes also tests outside of standard E5.1.
Duktape passes almost all of test262 cases, see
<a href="https://github.com/svaarala/duktape/blob/master/doc/test262-status.rst">test262-status.rst</a>
for current compatibility status.</p><h2 class="sectiontitle" id="compatibility-asmjs">Asm.js <a class="sectionlink" href="#compatibility-asmjs">§</a></h2><p><a href="http://asmjs.org/spec/latest/">asm.js</a> is a
"strict subset of JavaScript that can be used as a low-level, efficient
target language for compilers".  As a subset of JavaScript, functions using
asm.js type annotations should be fully compatible with Duktape.  However,
Duktape has no specific support for asm.js and won't optimize asm.js code.
In fact, asm.js code will generate unnecessary bytecode and execute slower
than normal Ecmascript code.  The <code>"use asm"</code> directive specified
by asm.js is ignored by Duktape.  Also, because there is not typed array
support yet, no "heap object" can be provided.</p><h2 class="sectiontitle" id="compatibility-emscripten">Emscripten <a class="sectionlink" href="#compatibility-emscripten">§</a></h2><p><a href="https://github.com/kripken/emscripten">Emscripten</a> compiles
C/C++ into Javascript.  Duktape is currently (as of Duktape 1.5.0) Emscripten
compatible and supports ES2015 TypedArray which allows Emscripten fastcomp
to be used.</p><p>Large programs may fail due to Duktape compiler running out of virtual
registers, and performance is somewhat limited as Duktape is an interpreted
engine.  See
<a href="https://github.com/svaarala/duktape/blob/master/doc/emscripten-status.rst">emscripten-status.rst</a>
for current compatibility status.</p><p>Because Duktape itself compiles with Emscripten, it is possible to run
Duktape inside a web page for instance, see
<a href="dukweb.html">Dukweb REPL</a>.
</p><h2 class="sectiontitle" id="compatibility-luajs">Lua.js <a class="sectionlink" href="#compatibility-luajs">§</a></h2><p><a href="https://github.com/mherkender/lua.js">lua.js</a> translates Lua
code to Javascript.  There are no known issues in running the generated
Javascript, except that Duktape doesn't provide <code>console.log</code>
which lua.js expects.  This is easy to remedy, e.g. by prepending the
following:</p><pre class="ecmascript-code"><span class="normal">console </span><span class="symbol">=</span><span class="normal"> </span><span class="cbracket">{</span><span class="normal"> log</span><span class="symbol">:</span><span class="normal"> </span><span class="keyword">function</span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span><span class="normal"> </span><span class="function">print</span><span class="symbol">(</span><span class="normal">Array</span><span class="symbol">.</span><span class="keyword">prototype</span><span class="symbol">.</span><span class="normal">join</span><span class="symbol">.</span><span class="function">call</span><span class="symbol">(</span><span class="normal">arguments</span><span class="symbol">,</span><span class="normal"> </span><span class="string">' '</span><span class="symbol">));</span><span class="normal"> </span><span class="cbracket">}</span><span class="normal"> </span><span class="cbracket">}</span><span class="symbol">;</span>
</pre><h2 class="sectiontitle" id="compatibility-jsinterpreter">JS-Interpreter <a class="sectionlink" href="#compatibility-jsinterpreter">§</a></h2><p><a href="https://github.com/NeilFraser/JS-Interpreter">JS-Interpreter</a>
interprets Javascript in Javascript.  JS-Interpreter works with Duktape,
except that Duktape doesn't provide <code>window</code> which JS-Interpreter
expects.  This can be fixed by prepending:</p><pre class="ecmascript-code"><span class="normal">window </span><span class="symbol">=</span><span class="normal"> </span><span class="cbracket">{}</span><span class="symbol">;</span>
</pre><hr/><h1 class="sectiontitle" id="versioning">Versioning <a class="sectionlink" href="#versioning">§</a></h1><h2 class="sectiontitle" id="semantic-versioning">Semantic versioning <a class="sectionlink" href="#semantic-versioning">§</a></h2><p>Duktape follows <a href="http://semver.org/">Semantic Versioning</a>:</p><ul>
<li>Major version changes when API incompatible changes are made.</li>
<li>Minor version changes when backwards-compatible functional changes are made.</li>
<li>Patch version changes when backwards-compatible bug fixes are made.</li>
</ul><p>The "public API" to which these rules apply include:</p><ul>
<li>The Duktape API calls documented on duktape.org; except those tagged
    <code>experimental</code>.</li>
<li>The global environment visible to Ecmascript code, including the <code>Duktape</code>
    object and other Ecmascript extensions, as documented on duktape.org;
    except changes needed to align with latest Ecmascript specifications.</li>
</ul><p>The following are not part of the "public API" versioning guarantees:</p><ul>
<li>Duktape API calls tagged <code>experimental</code>.</li>
<li>Internal calls made by API macros.  While API calls implemented as macros
    are part of the public API, any internal calls the macros make are not,
    even if their symbol visibility is public.</li>
<li>Changing an API call from a function call to a macro (or vice versa).
    These are considered compatible changes (but are not done in patch releases).</li>
<li>Aligning with latest Ecmascript specifications.  Duktape tracks the latest
    Ecmascript specification (currently ES2016).  Backwards incompatible changes
    required to align with the latest specifications may be done in minor
    versions too (but not in patch versions unless necessary to fix a bug).
    Typically such changes are relatively minor, for example argument coercion
    or property inheritance changes.</li>
<li>Specific behavior which is explicitly noted to potentially change even in
    minor versions, for example:
    <ul>
<li>Behavior of buffer objects when their backing buffer is smaller than
        the apparent size of the buffer object.  Memory safe behavior is
        guaranteed, but otherwise behavior may vary between versions.</li>
</ul>
</li>
<li>Duktape config options.  Incompatible config option changes are not made in
    patch releases, but can be made in minor releases.  The goal is to cause a
    compile error (if possible) when a no-longer-supported feature option is
    used so that any incorrect assumptions can be fixed.</li>
<li>Extras distributed with Duktape (<code>extras/</code> directory).</li>
</ul><p>When a patch version is released, the following things are guaranteed:</p><ul>
<li>API binary compatibility is maintained: constant values don't change, function
    typing doesn't change, API call function/macro status doesn't change.</li>
<li>Bytecode dump/load format doesn't change so that you can load bytecode
    dumped from an older version which only differs in patch version.</li>
<li>Ecmascript semantics fixes are not included unless necessary to fix
    a bug.</li>
<li>Config options won't change in an incompatible manner.</li>
</ul><h2 class="sectiontitle" id="experimental-features">Experimental features <a class="sectionlink" href="#experimental-features">§</a></h2><p>Some new features and API calls are marked <b>experimental</b> which means
that they may change in an incompatible way even in a minor release.</p><p>Features may be marked experimental e.g. because they are useful but
incomplete, or because the best design is not obvious and it's useful to
gather some feedback before committing to the design.  Typically a feature
is experimental for one minor release and then, after the necessary changes,
becomes a fully supported feature.</p><h2 class="sectiontitle" id="version-naming">Version naming <a class="sectionlink" href="#version-naming">§</a></h2><p>Releases use the form <i>(major).(minor).(patch)</i>, e.g. <b>1.0.3</b>.</p><p>Development pre-releases use the form <i>(major).(minor).(patch)-alpha.(number)</i>,
e.g. <b>1.3.0-alpha.2</b>.  The form <i>0.(minor).0</i> was used for development
pre-releases before the 1.0 release.</p><h2 class="sectiontitle" id="versioning.4">DUK_VERSION and Duktape.version <a class="sectionlink" href="#versioning.4">§</a></h2><p><code>DUK_VERSION</code> and <code>Duktape.version</code> provide version
identification using a single number computed as:
<code>(major * 10000 + minor * 100 + patch)</code>,
then subtracting one for development pre-releases.</p><p>Note the limitations for development pre-releases:</p><ul>
<li>Development pre-releases for the same release are not distinguished from
    one another: for example, both 1.3.0-alpha.1 and 1.3.0-alpha.2 are
    identified as 10299.</li>
<li>Development pre-releases for patch releases are not distinguished from the
    previous patch release: for example, 1.3.3-alpha.6 and 1.3.2 are both
    identified as 10302.</li>
</ul><p>Development pre-releases shouldn't be used in production, but the current
<code>DUK_VERSION</code> and <code>Duktape.version</code> number provides
a useful approximation for version comparison: an alpha release will compare
smaller than the actual release, but higher (or equal) than a previous release.</p><h2 class="sectiontitle" id="versioning-examples">Examples <a class="sectionlink" href="#versioning-examples">§</a></h2><p>The table below provides some examples, in ascending version order:</p><table>
<tr>
<th>Version</th>
<th>Pre-release?</th>
<th>DUK_VERSION &amp;<br/>Duktape.version</th>
<th>Notes</th>
</tr>
<tr><td>0.12.0</td><td>yes</td><td>1200</td><td>Pre-release before 1.0 release.</td></tr>
<tr><td>1.0.0</td><td>no</td><td>10000</td><td></td></tr>
<tr><td>1.3.0-alpha.1</td><td>yes</td><td>10299</td><td>Identified like 1.2.99, first 1.3.0 development pre-release.</td></tr>
<tr><td>1.3.0-alpha.2</td><td>yes</td><td>10299</td><td>Identified like 1.2.99, no difference to 1.3.0-alpha.1.</td></tr>
<tr><td>1.3.0</td><td>no</td><td>10300</td><td></td></tr>
<tr><td>1.3.2</td><td>no</td><td>10302</td><td></td></tr>
<tr><td>1.3.3-alpha.6</td><td>yes</td><td>10302</td><td>Identified like 1.3.2, no difference to 1.3.2 release.</td></tr>
<tr><td>1.3.3</td><td>no</td><td>10303</td><td></td></tr>
<tr><td>2.0.0-alpha.3</td><td>yes</td><td>19999</td><td>Identified like 1.99.99.</td></tr>
<tr><td>2.0.0</td><td>no</td><td>20000</td><td></td></tr>
</table><h2 class="sectiontitle" id="version-maintenance">Maintenance of stable versions <a class="sectionlink" href="#version-maintenance">§</a></h2><p>There's no long term maintenance policy yet: stable versions will get bug
fixes (patch releases) at least until the next stable version has been
released, and there has been some time to migrate to it.</p><h2 class="sectiontitle" id="versioning.7">Incompatible changes <a class="sectionlink" href="#versioning.7">§</a></h2><p>The general goal for incompatible changes is that an application relying
on old, unsupported features will fail to build.  It is preferable to have the
build fail rather than to be silently broken.  This means for example that:</p><ul>
<li>When API call semantics are changed, the old API call is removed (causing
    a build failure if used) and a new one is added.</li>
<li>When support for an old feature option is removed, an attempt to use it
    will cause a build failure.</li>
</ul><p>This is not a hard rule, but the default guideline.</p><hr/><h1 class="sectiontitle" id="limitations">Limitations <a class="sectionlink" href="#limitations">§</a></h1><p>The following is a list of known limitations of the current implementation.
Limitations include shortcomings from a semantics perspective, performance
limitations, and implementation limits (which are inevitable).</p><p>Trivial bugs are not listed unless they are "long term bugs".</p><h2 class="sectiontitle" id="limitations.1">No re-entrancy <a class="sectionlink" href="#limitations.1">§</a></h2><p>A single Duktape heap, i.e. contexts sharing the same garbage collector,
is <b>not re-entrant</b>.  Only one C/C++ thread can call Duktape APIs
at a time for a particular Duktape heap (although the calling thread
can change over time).  See <a href="#threading">Threading</a>.</p><h2 class="sectiontitle" id="limitations.2">String and buffer limits <a class="sectionlink" href="#limitations.2">§</a></h2><p>The internal representation allows a maximum length of 2**31-1 (0x7fffffff)
<i>bytes</i> (not characters) for strings.  16-bit codepoints encode into 3
bytes of UTF-8 in the worst case, so the maximum string length which is
guaranteed to work is about 0.7G characters.</p><p>Buffer values are also limited to 2**31-1 (0x7fffffff) bytes.</p><h2 class="sectiontitle" id="limitations.3">Property limits <a class="sectionlink" href="#limitations.3">§</a></h2><p>An object can have at most <code>DUK_HOBJECT_MAX_PROPERTIES</code> (an
internal define).  Currently this limit is 0x7ffffffff.</p><h2 class="sectiontitle" id="limitations.4">Array limits <a class="sectionlink" href="#limitations.4">§</a></h2><p>When array item indices go over the 2**31-1 limit (0x7fffffff), Duktape
has some known bugs with array semantics.</p><h2 class="sectiontitle" id="limitations.5">Regexp quantifier over empty match <a class="sectionlink" href="#limitations.5">§</a></h2><p>The regexp engine gets stuck when a quantifier is used over an
empty match but eventually bails out with an internal recursion
(or execution step) limit.  For instance, the following should produce
a "no match" result but hits an internal recursion limit instead:</p><pre>
$ duk
duk&gt; t = /(x*)*/.exec('y');
RangeError: regexp executor recursion limit
    at [anon] (duk_regexp_executor.c:145) internal
    at exec () native strict preventsyield
    at global (input:1) preventsyield
</pre><h2 class="sectiontitle" id="limitations.6">Duktape does not fully support locales <a class="sectionlink" href="#limitations.6">§</a></h2><p>Although Duktape supports the concept of a local time, it doesn't support
other locale related features such as: locale specific Date formatting,
locale specific string comparison, locale/language specific Unicode rules
(such as case conversion rules for Turkish, Azeri, and Lithuanian).</p><h2 class="sectiontitle" id="limitations.7">Unicode case conversion is not locale or context sensitive <a class="sectionlink" href="#limitations.7">§</a></h2><p>E5 Sections 15.5.4.16 to 15.5.4.19 require context and locale processing
of Unicode <code>SpecialCasing.txt</code>.  However, Duktape doesn't currently
have a notion of "current locale".</p><h2 class="sectiontitle" id="limitations.8">Array performance when using non-default property attributes <a class="sectionlink" href="#limitations.8">§</a></h2><p>All array elements are expected to be writable, enumerable, and configurable
(default property attributes for new properties).  If this assumption is violated,
even temporarily, the entire "array part" of an object is abandoned permanently
and array entries are moved to the "entry part".  This involves interning all used
array indices as explicit string keys (e.g. "0", "1", etc).  This is not a
compliance concern, but degrades performance.</p><h2 class="sectiontitle" id="limitations.9">Array performance when writing elements using Object.defineProperty() <a class="sectionlink" href="#limitations.9">§</a></h2><p>When number indexed array elements are written with <code>Object.defineProperty()</code>
the current implementation abandons the internal "array part" which makes later
array access much slower.  Write array elements with direct assignments such as
<code>a[123] = 321</code> to avoid this.</p><h2 class="sectiontitle" id="limitations.10">Global/eval code is slower than function code <a class="sectionlink" href="#limitations.10">§</a></h2><p>Bytecode generated for global and eval code cannot assign variables
statically to registers, and will use explicit name-based variable
read/write accesses.  Bytecode generated for function code doesn't
have this limitation; most variables are assigned statically to registers
and direct register references are used used to access them.</p><p>This is a minor issue unless you spend a lot of time running top-level
global/eval code.  The workaround is simple: put code in a function which
you call from the top level; for instance:</p><pre class="ecmascript-code"><span class="keyword">function</span><span class="normal"> </span><span class="function">main</span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="comment">// ...</span>
<span class="cbracket">}</span>
<span class="function">main</span><span class="symbol">();</span>
</pre><p>There is also a common idiom of using an anonymous function for this
purpose:</p><pre class="ecmascript-code"><span class="symbol">(</span><span class="keyword">function</span><span class="normal"> </span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="comment">// ...</span>
<span class="cbracket">}</span><span class="symbol">)();</span>
</pre><h2 class="sectiontitle" id="limitations.11">Function temporaries may be live for garbage collection longer than expected <a class="sectionlink" href="#limitations.11">§</a></h2><p>Ecmascript functions are compiled into bytecode with a fixed set of
registers.  Some registers are reserved for arguments and variable
bindings while others are used as temporaries.  All registers are
considered live from a garbage collection perspective, even temporary
registers containing old values which the function actually cannot
reference any more.  Such temporaries are considered reachable until they
are overwritten by the evaluation of another expression or until the
function exits.  Function exit is the only easily predicted condition to
ensure garbage collection.</p><p>If you have a function which remains running for a very long time, it
should contain the bare minimum of variables and temporaries that could
remain live.  For instance, you can structure code like:</p><pre class="ecmascript-code"><span class="keyword">function</span><span class="normal"> </span><span class="function">runOnce</span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="comment">// run one iteration, lots of temporaries</span>
<span class="cbracket">}</span>

<span class="keyword">function</span><span class="normal"> </span><span class="function">foreverLoop</span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="keyword">for</span><span class="normal"> </span><span class="symbol">(;;)</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">        </span><span class="function">runOnce</span><span class="symbol">();</span>
<span class="normal">    </span><span class="cbracket">}</span>
<span class="cbracket">}</span>
</pre><p>This is typically not an issue if there are no long-running functions.</p><h2 class="sectiontitle" id="limitations.12">Function instances are garbage collected only by mark-and-sweep <a class="sectionlink" href="#limitations.12">§</a></h2><p>Every Ecmascript function instance is, by default, in a reference loop with
an automatic prototype object created for the function.  The function instance's
<code>prototype</code> property points to the prototype object, and the prototype's
<code>constructor</code> property points back to the function instance.  Only
mark-and-sweep is able to collect these reference loops at the moment.  If you
build with reference counting only (not recommended), function instances may
appear to leak memory; the memory will be released when the relevant heap is
destroyed.</p><p>You can break the reference loops manually (although this is a bit cumbersome):</p><pre class="ecmascript-code"><span class="keyword">var</span><span class="normal"> f </span><span class="symbol">=</span><span class="normal"> </span><span class="keyword">function</span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span><span class="normal"> </span><span class="cbracket">}</span><span class="symbol">;</span>
<span class="keyword">var</span><span class="normal"> g </span><span class="symbol">=</span><span class="normal"> </span><span class="keyword">function</span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span><span class="normal"> </span><span class="cbracket">}</span><span class="symbol">;</span>
<span class="keyword">var</span><span class="normal"> h </span><span class="symbol">=</span><span class="normal"> </span><span class="keyword">function</span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span><span class="normal"> </span><span class="cbracket">}</span><span class="symbol">;</span>
<span class="normal">Duktape</span><span class="symbol">.</span><span class="function">fin</span><span class="symbol">(</span><span class="normal">f</span><span class="symbol">,</span><span class="normal"> </span><span class="keyword">function</span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span><span class="normal"> </span><span class="function">print</span><span class="symbol">(</span><span class="string">'finalizer for f'</span><span class="symbol">);</span><span class="normal"> </span><span class="cbracket">}</span><span class="symbol">);</span>
<span class="normal">Duktape</span><span class="symbol">.</span><span class="function">fin</span><span class="symbol">(</span><span class="normal">g</span><span class="symbol">,</span><span class="normal"> </span><span class="keyword">function</span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span><span class="normal"> </span><span class="function">print</span><span class="symbol">(</span><span class="string">'finalizer for g'</span><span class="symbol">);</span><span class="normal"> </span><span class="cbracket">}</span><span class="symbol">);</span>
<span class="normal">Duktape</span><span class="symbol">.</span><span class="function">fin</span><span class="symbol">(</span><span class="normal">h</span><span class="symbol">,</span><span class="normal"> </span><span class="keyword">function</span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span><span class="normal"> </span><span class="function">print</span><span class="symbol">(</span><span class="string">'finalizer for h'</span><span class="symbol">);</span><span class="normal"> </span><span class="cbracket">}</span><span class="symbol">);</span>

<span class="comment">// not collected until heap destruction in a reference counting only build</span>
<span class="normal">f </span><span class="symbol">=</span><span class="normal"> </span><span class="keyword">null</span><span class="symbol">;</span><span class="normal">            </span><span class="comment">// not collected immediately</span>

<span class="comment">// break cycle by deleting 'prototype' reference (alternative 1)</span>
<span class="normal">g</span><span class="symbol">.</span><span class="keyword">prototype</span><span class="normal"> </span><span class="symbol">=</span><span class="normal"> </span><span class="keyword">null</span><span class="symbol">;</span>
<span class="normal">g </span><span class="symbol">=</span><span class="normal"> </span><span class="keyword">null</span><span class="symbol">;</span><span class="normal">            </span><span class="comment">// collected immediately, finalizer runs</span>

<span class="comment">// break cycle by deleting 'constructor' reference (alternative 2)</span>
<span class="normal">h</span><span class="symbol">.</span><span class="keyword">prototype</span><span class="symbol">.</span><span class="normal">constructor </span><span class="symbol">=</span><span class="normal"> </span><span class="keyword">null</span><span class="symbol">;</span>
<span class="normal">h </span><span class="symbol">=</span><span class="normal"> </span><span class="keyword">null</span><span class="symbol">;</span><span class="normal">            </span><span class="comment">// collected immediately, finalizer runs</span>

<span class="comment">// no-op with refcount only, with mark-and-sweep finalizer for 'f' runs</span>
<span class="normal">Duktape</span><span class="symbol">.</span><span class="function">gc</span><span class="symbol">();</span>
</pre><p>For internal technical reasons, named function expressions are also in a
reference loop with an internal environment record object.  This loop cannot
be broken from user code and only mark-and-sweep can collect such functions.
Ordinary function declarations and anonymous functions don't have this
limitation.  Example:</p><pre class="ecmascript-code"><span class="keyword">var</span><span class="normal"> fn </span><span class="symbol">=</span><span class="normal"> </span><span class="keyword">function</span><span class="normal"> </span><span class="function">myfunc</span><span class="symbol">()</span><span class="normal"> </span><span class="cbracket">{</span>
<span class="normal">    </span><span class="comment">// myfunc is in reference loop with an internal environment record,</span>
<span class="normal">    </span><span class="comment">// and can only be collected with mark-and-sweep.</span>
<span class="cbracket">}</span>
</pre><p>Since Duktape 2.x mark-and-sweep is always enabled so that objects
participating in reference loops are eventually freed.  You can disable
periodic "voluntary" (non-emergency) mark-and-sweep via config options
to reduce collection pauses in time sensitive environments.</p><h2 class="sectiontitle" id="limitations.13">Non-standard function 'caller' property limitations <a class="sectionlink" href="#limitations.13">§</a></h2><p>When <code>DUK_USE_NONSTD_FUNC_CALLER_PROPERTY</code> is given, Duktape
updates the <code>caller</code> property of non-strict function instances
similarly to e.g. V8 and
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller">Spidermonkey</a>.
There are a few limitations, though:</p><ul>
<li>When a (non-strict) function is called from eval code, Duktape sets
    <code>caller</code> to <code>null</code> if the eval code is non-strict,
    and <code>eval</code> (reference to the eval built-in function) if the
    eval code is strict.  This deviates from e.g. V8 behavior.</li>
<li>Coroutines and <code>caller</code> don't mix well: <code>caller</code>
    may be left in a non-<code>null</code> state even after coroutine call
    stacks have been fully unwound.  Also, if a coroutine is garbage collected
    before its call stack is unwound, the <code>caller</code> property of
    functions in its call stack will not get updated now.</li>
</ul><p>See the internal <code>test-bi-function-nonstd-caller-prop.js</code> test
case for further details.</p><h2 class="sectiontitle" id="limitations.14">Garbage collection during debugger paused state <a class="sectionlink" href="#limitations.14">§</a></h2><p>When debugger support is activated, a debugger session is active, and
Duktape is paused, there are a few current limitations:</p><ul>
<li>Because garbage collection is disabled during the paused state, calls to
    <code>Duktape.gc()</code> and <code>duk_gc()</code> will be silently
    ignored.</li>
</ul><hr/><h1 class="sectiontitle" id="comparisontolua">Comparison to Lua <a class="sectionlink" href="#comparisontolua">§</a></h1><p>Duktape borrows a lot from Lua conceptually.  Below are a few notes on
what's different in Duktape compared to Lua.  This may be useful if you're
already familiar with Lua.</p><h2 class="sectiontitle" id="comparisontolua.1">Array and stack indices are zero-based <a class="sectionlink" href="#comparisontolua.1">§</a></h2><p>All array and stack indices are zero-based, not one-based as in Lua.  So,
bottom of stack is 0, second element from bottom is 1, and top element is -1.
Because 0 is no longer available to denote an invalid/non-existent element,
the constant <code>DUK_INVALID_INDEX</code> is used instead in Duktape.</p><p>String indices are also zero-based, and slices are indicated with an
inclusive start index and an exclusive end index (i.e. [start,end[).
In Lua, slices are indicated with inclusive indices (i.e. [start,end]).</p><h2 class="sectiontitle" id="comparisontolua.2">Object type represents functions and threads <a class="sectionlink" href="#comparisontolua.2">§</a></h2><p>In Lua functions and threads are a separate type from objects.
In Duktape the object type is used for plain objects, Ecmascript and
native functions, and threads (coroutines).  As a result, all of these
have a mutable and extensible set of properties.</p><h2 class="sectiontitle" id="comparisontolua.3">Lua userdata and lightuserdata <a class="sectionlink" href="#comparisontolua.3">§</a></h2><p>The concept closest to Lua <code>userdata</code> is the Duktape <code>buffer</code>
type, with the following differences:</p><ul>
<li>Duktape buffers can be resizable, Lua userdata values cannot.  If a
    Duktape buffer is resizable, its data pointer is no longer guaranteed
    to be stable.</li>
<li>Duktape buffers are raw byte arrays without any properties, Lua userdata
    objects can store an environment reference.</li>
</ul><p>Lua <code>lightuserdata</code> and Duktape <code>pointer</code> are essentially
the same.</p><p>If you need to associate properties with a Duktape buffer, you can use
a buffer object instead (or create your own object and store the plain buffer
as its property).  You can then add a finalizer to the object to free any
resources related to the buffer.  This works reasonably well as long as nothing
else holds a reference to the buffer.  If this were the case, the buffer could
get used after the object had already been finalized.  To safeguard against this,
the native C structure should have a flag indicating whether the data structure
is open or closed.  This is good practice anyway for robust native code.</p><h2 class="sectiontitle" id="comparisontolua.4">Garbage collection <a class="sectionlink" href="#comparisontolua.4">§</a></h2><p>Duktape has a combined reference counting and non-incremental mark-and-sweep
garbage collector (mark-and-sweep is needed only for reference cycles).  Collection
pauses can be avoided by disabling voluntary mark-and-sweep passes
(disable <code>DUK_USE_VOLUNTARY_GC</code>).  Lua has an incremental collector with
no pauses, but has no reference counting.</p><p>Duktape has an emergency garbage collector.  Lua 5.2 has an emergency
garbage collector while Lua 5.1 does not (there is an emergency GC patch
though).</p><h2 class="sectiontitle" id="comparisontolua.5">duk_safe_call() vs. lua_cpcall() <a class="sectionlink" href="#comparisontolua.5">§</a></h2><p><code>duk_safe_call()</code> is a protected C function call which
operates in the existing value stack frame.  The function call is
not visible on the call stack all.</p><p><code>lua_cpcall()</code> creates a new stack frame.</p><h2 class="sectiontitle" id="comparisontolua.6">Bytecode dump/load <a class="sectionlink" href="#comparisontolua.6">§</a></h2><p>Starting from Duktape 1.3 Duktape has a bytecode dump/load mechanism
similar to Lua <code>lua_dump()</code>. See
<a href="#bytecodedumpload">Bytecode dump/load</a>.</p><h2 class="sectiontitle" id="comparisontolua.7">Metatables <a class="sectionlink" href="#comparisontolua.7">§</a></h2><p>There is no equivalent of Lua metatables in Ecmascript E5/E5.1, but
<a href="http://www.ecma-international.org/ecma-262/6.0/index.html#sec-proxy-objects">Ecmascript E6 Proxy objects</a>
provide similar functionality.  To allow property virtualization better than available in
E5/E5.1, Duktape implements an <a href="#es6-proxy">ES2015 Proxy subset</a>.</p><h2 class="sectiontitle" id="comparisontolua.8">lua_next() vs. duk_next() <a class="sectionlink" href="#comparisontolua.8">§</a></h2><p><code>lua_next()</code> replaces the previous key and value with a new pair,
while <code>duk_next()</code> does not; the caller needs to explicitly pop the
key and/or value.</p><h2 class="sectiontitle" id="comparisontolua.9">Raw accessors <a class="sectionlink" href="#comparisontolua.9">§</a></h2><p>There is no equivalent to Lua raw table access functions like
<code>lua_rawget</code>.  One can use the following Ecmascript built-ins
for a similar effect (though not with respect to performance):
<a href="http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.3.3">Object.getOwnPropertyDescriptor ( O, P )</a>,
<a href="http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.3.6">Object.defineProperty ( O, P, Attributes )</a>.</p><h2 class="sectiontitle" id="comparisontolua.10">Coroutines <a class="sectionlink" href="#comparisontolua.10">§</a></h2><p>There are no primitives for coroutine control in the Duktape API
(Lua API has e.g. <code>lua_resume</code>).  Coroutines can only be controlled
using the functions exposed by the <code>Duktape</code> built-in.  Further,
Duktape has quite many coroutine yield restrictions now; for instance,
coroutines cannot yield from inside constructor calls or getter/setter calls.</p><h2 class="sectiontitle" id="comparisontolua.11">Multiple return values <a class="sectionlink" href="#comparisontolua.11">§</a></h2><p>Lua supports multiple return values, Duktape (or Ecmascript) currently
doesn't.  This may change with Ecmascript E6, which has a syntax for
multiple value returns.  The Duktape/C API reserves return values above 1
so that they may be later used for multiple return values.</p><h2 class="sectiontitle" id="comparisontolua.12">Weak references <a class="sectionlink" href="#comparisontolua.12">§</a></h2><p>Lua supports weak references.  Duktape currently doesn't.</p><h2 class="sectiontitle" id="comparisontolua.13">Unicode <a class="sectionlink" href="#comparisontolua.13">§</a></h2><p>Lua has no built-in Unicode support (strings are byte strings), while
Duktape has support for 16-bit Unicode as part of Ecmascript compliance.</p><h2 class="sectiontitle" id="comparisontolua.14">Streaming compilation <a class="sectionlink" href="#comparisontolua.14">§</a></h2><p>Lua has a streaming compilation API which is good when code is read from
the disk or perhaps decompressed on-the-fly.  Duktape currently does not
support streaming compilation because it needs multiple passes over the
source code.</p></div> <!-- site-middle-content -->
</div> <!-- site-middle -->
<div id="site-bottom">
<hr/>
<p>Duktape is (C) by its <a href="https://github.com/svaarala/duktape/blob/master/AUTHORS.rst">authors</a>
and licensed under the <a href="https://github.com/svaarala/duktape/blob/master/LICENSE.txt">MIT license</a>.</p>
</div> <!-- site-bottom -->
</body>
</html>